要研究怎麼做,先得搞清楚需要做什麼
根據剛纔的學習,做基本的Hibernate應用程序,要完成下面的工作:Object、數據庫的表、兩種配置文件、客戶端程序來調用Hibernate的接口進行操作。
構建環境
最簡單的方法:把hibernate-release-4.0.0.Beta4.zip包裏面lib/required下的jar包全部添加到工程的library裏面,另外還需添加slf4j的實現包slf4j-log4j12-1.5.8.jar和log4j的實現包log4j-1.2.16.jar,還有別忘了把JDBC的驅動jar包也加入到library裏面
Object怎麼做
1:就是前面學過的vo的寫法(規則同樣是那四點)
2:要求必須有一個public爲空參的構造方法,現在寫vo一般不寫構造方法,默認就有一個,但是寫構造方法的時候要注意寫上一個public爲空參的構造方法
3:要求提供一個標識屬性(identifier)
4:使用非final的類(因爲要使用代理來延遲實體的裝載)
5:設若構建一個對象:cn.javass.h4.hello.UserModel,有四個屬性:uuid,userId,name,age
在數據庫中建表
設若構建一個表爲tbl_user,字段:uuid,userId,name,age
配置xxx.cfg.xml
1:缺省名稱爲 hibernate.cfg.xml
2:存放在當前classes的根目錄下,開發的時候在src根下就可以了
3:主要有如下四部分配置 :
(1)與DB的連接
(2)可選配置
(3)資源文件註冊
(4)二級緩存
4:配置的時候可以到Hibernate發行包裏面找個hibernate.cfg.xml的例子,比如可以用“\project\hibernate-documentation\quickstart\tutorials\basic\src\test\resources”下面的hibernate.cfg.xml作例子
5:示例如下:
java代碼:
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
- <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
- <property name="connection.username">test</property>
- <property name="connection.password">test</property>
- <property name="connection.pool_size">2</property>
- <property name="dialect">org.hibernate.dialect.OracleDialect</property>
- <property name="show_sql">true</property>
- <mapping resource="cn/javass/h4/hello/UserModel.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="connection.pool_size">2</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<mapping resource="cn/javass/h4/hello/UserModel.hbm.xml"/>
</session-factory>
</hibernate-configuration>
配置xxx.hbm.xml
1:與被描述的類同名 ,如:UserModel.hbm.xml
2:存放位置與所描述類存放在同一文件夾下
3:主要有如下四部分配置 :
(1)類和表的映射
(2)主鍵的映射
(3)類的屬性和DB中字段的映射
(4)關係的映射
4:配置的時候可以到hibernate發行包裏面找個例子,比如可以用“\project\hibernate-core\src\test\java\org\hibernate\test\cid”下面的Customer.hbm.xml作例子
5:示例如下:
java代碼:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- '-//Hibernate/Hibernate Mapping DTD 3.0//EN'
- 'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
- <hibernate-mapping>
- <class name="cn.javass.h4.hello.UserModel" table="tbl_user">
- <id name="uuid">
- <generator class="assigned"/>
- </id>
- <property name=“userId”></property>
- <property name=“name”></property>
- <property name="age"></property>
- </class>
- </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
'-//Hibernate/Hibernate Mapping DTD 3.0//EN'
'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
<hibernate-mapping>
<class name="cn.javass.h4.hello.UserModel" table="tbl_user">
<id name="uuid">
<generator class="assigned"/>
</id>
<property name=“userId”></property>
<property name=“name”></property>
<property name="age"></property>
</class>
</hibernate-mapping>
客戶端文件:
java代碼:
- package cn.javass.h4.hello;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- public class Client {
- public static
void main(String[] args) {
- SessionFactory sf = new Configuration().configure().buildSessionFactory();
- Session s = null;
- Transaction t = null;
- try{
-
- UserModel um = new UserModel();
- um.setUuid("1");
- um.setUserId("id1");
- um.setName("name1");
- um.setAge(1);
- s = sf.openSession();
- t = s.beginTransaction();
- s.save(um);
- t.commit();
- }catch(Exception err){
- t.rollback();
- err.printStackTrace();
- }finally{
- s.close();
- }
- }
- }
package cn.javass.h4.hello;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Client {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = null;
Transaction t = null;
try{
//準備數據
UserModel um = new UserModel();
um.setUuid("1");
um.setUserId("id1");
um.setName("name1");
um.setAge(1);
s = sf.openSession();
t = s.beginTransaction();
s.save(um);
t.commit();
}catch(Exception err){
t.rollback();
err.printStackTrace();
}finally{
s.close();
}
}
}
測試:直接在Elipse裏面運行Client文件即可,運行結束,你將會看到在console輸出:“Hibernate: insert into tbl_user (userId, name, age, uuid) values (?, ?, ?, ?)”,打開數據庫的數據表,你會看到一條值已經加入了。
說明:
1:SessionFactory sf = new Configuration().configure().buildSessionFactory();這句話的意思是讀取hibernate.cfg.xml,創建Session工廠,是線程安全的。
默認是”hibernate.cfg.xml”,不用寫出來,如果文件名不是”hibernate.cfg.xml”,那麼需要顯示指定,如下:
SessionFactory sf = new Configuration(). configure( “javass.cfg.xml”).buildSessionFactory();
2:Session是應用程序主要使用的Hibernate接口,約相當於JDBC的Connection+Statement/PreparedStatement的功能,是線程不安全的
3:在Hibernate4裏面,已經不推薦使用Configuration類了,而改爲使用 ServiceRegistryBuilder和MetadataSources來代替,新的寫法大致如下:
ServiceRegistryBuilder builder = new ServiceRegistryBuilder().configure();
builder.applySetting("connection.driver_class", "oracle.jdbc.driver.OracleDriver");
builder.applySetting("connection.url", "jdbc:oracle:thin:@localhost:1521:orcl");
builder.applySetting("connection.username", "ztb");
builder.applySetting("connection.password", "ztb");
builder.applySetting("connection.pool_size", "2");
builder.applySetting("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
builder.applySetting("show_sql", "true");
MetadataSources sources = new MetadataSources( builder.buildServiceRegistry() );
sources.addResource("cn/javass/h4/hello/UserModel.hbm.xml");
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
SessionFactory sf = metadata.getSessionFactoryBuilder().buildSessionFactory();
這種寫法,現在還沒有實現完全,不太好用,所以官方給出的示例裏面還是採用以前的方式,大家先了解一下。
4:這裏使用的事務Transaction是Hibernate的Transaction,需要有,不能去掉。