Hibernate中解決No Hibernate Session bound to thread問題


引用:忘了

 

首先是getCurrentSession()與openSession()的區別:

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 的方法。

 

那么當使用getCurrentSession()方法時報No Hibernate Session bound to thread問題該怎么辦呢?引用自http://www.cnblogs.com/ylhssn/p/5181149.html)

  1、getCurrentSession()是必須提交事務的。所以在用到session.getCurrentSession()的這個方法一定是要配置聲明式事務管理。

  2、openSession()恰恰是與以上的方法想法,它不需要提交事務。但是他的資源必須手動關閉。

  所以針對“No Hibernate Session bound to thread”異常的解決方案有兩個:

    方案一:將getCurrentSession()改為openSession()。

    方案二:在sessionFactory bean中的hibernateProperties項中配置以下信息:

1 <prop key="hibernate.current_session_context_class"> 2  thread 3 </prop> 4 <prop key="hibernate.transaction.factory_class"> 5   org.hibernate.transaction.JDBCTransactionFactory 6 </prop>

    在sessionFactory bean中添加以上兩條配置信息后,再次運行程序,又報異常!

org.hibernate.HibernateException: createCriteria is not valid without active transaction 

   已知使用getCurrentSession()方法是必須提交事務的,而在SSH框架中是使用spring配置聲明式事務管理的。

  那接下來再次復習一下spring配置聲明式事務管理知識,以便查找錯誤。

 

spring配置聲明式事務管理

此處知識回顧引自“一個無聊的人”的“Spring聲明式事務配置管理方法”,博主講的很詳細,推薦一看, 傳送門

以下是博文內容截圖:

 

  除此之外還可以使用其他幾種方式用spring管理事務,請自行查找資料學習。


  仔細核對項目中的配置信息后,確定事務已配置無誤,當前異常信息還是未解決,繼續找資料,最終在“如果你報createSQLQuery is not valid without active transaction,請看這里”一文中找到解決方式:

  將hibernate.current_session_context_class的值由Thread改為org.springframework.orm.hibernate2.SpringSessionContext

  至此由使用getCurrentSession()方法引發的異常問題解決!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM