1徘铝,在網(wǎng)上下載hibernate的發(fā)行包
這里是這個版本的:hibernate-distribution-3.6.10.Final
《hibernate下載網(wǎng)址》
2赌渣,導入jar包
1)hibernate3.jar
2)這個文件夾下的jar包:
hibernate-distribution-3.6.10.Final\lib\jpa
3)這個文件下的jar包:
hibernate-distribution-3.6.10.Final\lib\required
3,找到文件夾下的教程
在這個文件夾下
documentation\manual\zh-CN\html的index.html
4灌曙,加入配置文件,導入兩個DTD文件
文件夾是
hibernate-distribution-3.6.10.Final\hibernate3\org\hibernate
分別是
hibernate-configuration-3.0.dtd
hibernate-mapping-3.0.dtd
5尖飞,在hibernate.cfg.xml文件中配置一些基本的信息
1)配置數(shù)據(jù)庫的參數(shù)
property name="connection.driver_class"
2)配置數(shù)據(jù)庫的方言
property name="dialect"
3)是否顯示sql語句
property name="show_sql"
4)配置自動建表
property name="hbm2ddl.auto"
5)配置映射文件
mapping resource="com/huihui/day05/one2one/person.hbm.xml"
6,配置文件person.hbm.xml
7,測試配置插入數(shù)據(jù)的正確性
//1,創(chuàng)建配置對象
Configuration config=new Configuration();
//2,讀取配置文件
config.configure();
//3,更據(jù)配置文件信息創(chuàng)建一級緩存启泣,SessionFactory
SessionFactory factory=config.buildSessionFactory();
//創(chuàng)建會話,打開會話
Session session=factory.openSession();
//開啟事物
Transaction tran=session.beginTransaction();
//session的關(guān)閉
session.save(new User(null, "ZHANG", 10000.0, new Date()));
//事物的提交
tran.commit();
開啟一次會話之后可以啟動多個事件示辈,每個事件只有提交之后才會保存到數(shù)據(jù)庫寥茫,當調(diào)用回滾方法時數(shù)據(jù)會回到最后一次提交事件的時刻。
8矾麻,封裝第七條(7纱耻,)的代碼
1)設(shè)置成靜態(tài)代碼塊,就是為了避免多次調(diào)用配置文件的方法
2)ThreadLocal這個類是用來保存Session险耀,只有當前線程可以訪問膝迎,確保service層和dao層的session一致。為什么要確保一致呢胰耗?因為如果將事物的處理寫在dao層會出現(xiàn)事物異常。比如轉(zhuǎn)賬的時候A轉(zhuǎn)B芒涡,A扣了100元柴灯,B的賬戶凍結(jié)就會出現(xiàn)異常,這里面的是事物的邏輯需要保持session的一致费尽。
private static SessionFactory factory;
//用于存放session,該對象是線程安全的赠群,只有當前線程才能訪問
private static ThreadLocal<Session> threadLocal;
static{
Configuration config = new Configuration();
config.configure();
factory = config.buildSessionFactory();
threadLocal = new ThreadLocal<Session>();
}
public static Session getSession(){
Session session = threadLocal.get();
if(session==null || !session.isOpen()){
session = factory.openSession();
threadLocal.set(session);
}
return session;
}