前言:1 getCurrentSession創建的session會和綁定到當前線程,而openSession不會。
2 getCurrentSession創建的線程會在事務回滾或事物提交后自動關閉,而openSession必須手動關閉
這里getCurrentSession本地事務(本地事務:jdbc)時 要在配置文件里進行如下設置
* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>
本人新手,在整合Spring 4.x + Hibernate 4.x 時想用 getCurrentSession()來獲取session,然后並不是 一句sessionFactory.getCurrentSession()就簡單解決的。。。。。
在其他配置都已完成的情況下加上
spring管理事務
獲取session。。。。。執行save(e)方法。。。。
Error 
百度后發現,原因出現在 hibernate.current_session_context_class = thread 這句話上。當單獨使用hibernate的時候,這句話就起作用了。在使用本地JDBC事務下,此時的創建的session就會被綁定到當前線程中。而我之前在配置的時候使用的是spring來管理事務,所以報錯。
改: 
Error "No Session found for current thread"
百度發現:SessionFactory的getCurrentSession並不能保證在沒有當前Session的情況下會自動創建一個新的,這取決於 CurrentSessionContext的實現,SessionFactory將調用CurrentSessionContext的 currentSession()方法來獲得Session。在Spring中,如果我們在沒有配置TransactionManager並且沒有事先調 用SessionFactory.openSession()的情況直接調用getCurrentSession(),那么程序將拋出“No Session found for current thread”異常
之前我已經配置過TransactionManager了,怎么還會報錯呢? 最后發現原來之前的配置 expression表達式寫錯了。。。細節決定成敗!
