Hibernate學習之SessionFactory的opensession 和 getCu...

1 。 Hibernate 的 Id 生成策略
XXOO.hbm.xml 下 class 標籤的 主鍵id 標籤中 使用 <generator/> 標籤指定 生成策略。
<hibernate-mapping>
<class name="com.myeclipse.OneToOne.Student2" table="student2" catalog="hibernate">
<id name="id" type="long">
<column name="id" />
<!--xml中配置id生成策略 -->
<generator class="increment" /> 指定生成策略。
</id> 》》》》》》》》 下面部分省略。《《《《《《《
2. 關於SessionFactory 的取得session的方法:opensession()和 getCurrentSession() 的分析認知
簡單代碼以下:
Session session = sf.openSession() ; // 生成一個session
Session session2 = sf.getCurrentSession(); // 取得一個當前的Session
Session session3 = sf.getCurrentSession(); // 取得當前session
只要沒有提交事務 當前會話 (current session 就一直存在的。之後用 getCurrentSession 取得的session 都是同一個。)
System.out.println("不該該是false啊??"+(session2 == session));
System.out.println("這個呢??"+(session2 == session3));
結果:
false
true
調試發現:
首先發現 這三個session的 id 是這樣的。。 session2 與session3的id 是相等的。
分析:
session1 採用opensession方法取得的session ,無論有無當前會話,都要直接新開一個session。
session2 session3 採用getCurrentsession方法得到,
兩個方法取得的session 不同】
A Session begins when it is first needed, when the first call to getCurrentSession() is made.
It is then bound by Hibernate to the current thread.
1 getCurrentSession建立的session會和綁定到當前線程,而openSession不會。
2 getCurrentSession建立的線程會在事務回滾或事物提交後自動關閉,而openSession必須手動關閉
getCurrentSession () 使用當前的session openSession() 從新創建一個新的session
相關文章
相關標籤/搜索