hibernate關於session的關閉問題

一、getCurrentSession()與openSession()的區別?session

* 採用getCurrentSession()建立的session會綁定到當前線程中,而採用openSession(),建立的session則不會spa

* 採用getCurrentSession()建立的session在commit或rollback時會自動關閉,而採用openSession(),建立的session必須手動關閉hibernate

二、使用getCurrentSession()須要在hibernate.cfg.xml文件中加入以下配置:線程

* 若是使用的是本地事務(jdbc事務)orm

<property name="hibernate.current_session_context_class">thread</property>xml

* 若是使用的是全局事務(jta事務)事務

<property name="hibernate.current_session_context_class">jta</property>get


openSession() 與 getCurrentSession() 有何不一樣和關聯呢?it

在 SessionFactory 啓動的時候, Hibernate 會根據配置建立相應的 CurrentSessionContext ,在getCurrentSession() 被調用的時候,實際被執行的方法是 CurrentSessionContext.currentSession() 。在currentSession() 執行時,若是當前 Session 爲空, currentSession 會調用 SessionFactory 的 openSession 。因此 getCurrentSession() 對於 Java EE 來講是更好的獲取 Session 的方法。io


許多時候出現session is close();緣由就是你在hibernate.cfg.xml裏面設置了

<property name="hibernate.current_session_context_class">thread</property>

系統在commit();執行完以後就關閉了session,這時候你手動再關閉session就固然提示錯誤了

相關文章
相關標籤/搜索