本文研究的主要是hibernate關于session的關閉,具體如下。
1
2
3
4
5
6
7
8
9
|
Student student = new Student(); student.setName( "Jan" ); student.setAge( "22" ); student.setAddress( "廣東省肇慶市" ); Session session =HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(student); session.flush(); session.getTransaction().commit(); |
1、getCurrentSession()與openSession()的區別?
-
采用
getCurrentSession()
創建的session會綁定到當前線程中,而采用openSession()
,創建的session則不會 -
采用
getCurrentSession()
創建的session在commit或rollback時會自動關閉,而采用openSession()
,創建的session必須手動關閉
2、使用getCurrentSession()
需要在hibernate.cfg.xml文件中加入如下配置:
- 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
- 如果使用的是全局事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>
openSession()
與 getCurrentSession()
有何不同和關聯呢?
在 SessionFactory 啟動的時候, Hibernate 會根據配置創建相應的 CurrentSessionContext ,在getCurrentSession()
被調用的時候,實際被執行的方法是 CurrentSessionContext.currentSession()
。在currentSession()
執行時,如果當前 Session 為空, currentSession 會調用 SessionFactory 的 openSession 。所以 getCurrentSession()
對于 Java EE 來說是更好的獲取 Session 的方法。
許多時候出現session is close();
原因就是你在hibernate.cfg.xml里面設置了
1
|
< property name = "hibernate.current_session_context_class" >thread</ property > |
系統在commit();
執行完之后就關閉了session,這時候你手動再關閉session就當然提示錯誤了
總結
以上就是本文關于hibernate關于session的關閉實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/u011202334/article/details/46500493