解決No Hibernate Session bound to thread
背景交代
在使用this.getHibernateTemplate().getSessionFactory().getCurrentSession()方法獲取session時報以下異常信息:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and conf iguration does not allow creation of non-transactional one here
在SSH架構中,spring如何對事務和hibernate session進行管理
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()方法引發的異常問題解決!