1. 程式人生 > >openSession() 跟 getCurrentSession() 方法之間的區別

openSession() 跟 getCurrentSession() 方法之間的區別

getHiberanteTemplate 、getCurrentSession和OpenSession  採用getCurrentSession()建立的Session會繫結到當前的執行緒中去、而採用OpenSession()則不會。

採用getCurrentSession()建立的Session在commit或rollback後會自動關閉,採用OpenSession()必須手動關閉。

採用getCurrentSession()需要在Hibernate.cfg.xml配置檔案中加入如下配置:

如果是本地事物,及JDBC一個數據庫:

<propety name=”Hibernate.current_session_context_class”>thread</propety>

如果是全域性事物,及jta事物、多個數據庫資源或事物資源:

<propety name=”Hibernate.current_session_context_class”>jta</propety>

使用spring的getHiberanteTemplate 就不需要考慮事務管理和session關閉的問題:

openSession建立session時autoCloseSessionEnabled引數為false,即在事物結束後不會自動關閉session,需要手動關閉,如果不關閉將導致session關聯的資料庫連線無法釋放,最後資源耗盡而使程式當掉。              

getCurrentSession建立session時autoCloseSessionEnabled,flushBeforeCompletionEnabled都為true,並且session會同sessionFactory組成一個map以sessionFactory為主鍵繫結到當前執行緒。

getCurrentSession():從上下文(配置檔案current_session_context_class: thread 使用Connection自動管理;jta(java transaction api) 由Application Server提供的分散式事務管理,Tomcat本身不具備此能力,JBoss、WebLogic具備)找,如果有,則用舊的,否則建立新的,事務提交自動Close;

getCurrentSession本地事務(本地事務:jdbc)時 要在配置檔案裡進行如下設定:

如果使用的是本地事務(jdbc事務) <property name="hibernate.current_session_context_class">thread</property> 如果使用的是全域性事務(jta事務) <property name="hibernate.current_session_context_class">jta</property>

總之:

 getCurrentSession () 使用當前的session  openSession()         重新建立一個新的session

 在一個應用程式中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命週期,則首選getCurrentSession ()。