1. 程式人生 > >轉:Could not commit Hibernate 問題,spring 事物 提交前session關閉問題

轉:Could not commit Hibernate 問題,spring 事物 提交前session關閉問題

org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
最近在寫操作CLOB的過程中總是報這個異常,資料去插入進去了.


先看看SessionFactory.getCurrentSession與openSession的區別
1. 如果使用的是getCurrentSession來建立session的話,在commit後,session就自動被關閉了,
    也就是不用再session.close()了。但是如果使用的是openSession方法建立的session的話,
    那麼必須顯示的關閉session,也就是呼叫session.close()方法。這樣commit後,session並沒有關閉
/*2. getCurrentSession的使用可以參見hibernate\hibernate-3.2\doc\tutorial\src專案
3. 使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
   * 如果採用jdbc獨立引用程式配置如下:
    <property name="hibernate.current_session_context_class">thread</property>
   * 如果採用了JTA事務配置如下
    <property name="hibernate.current_session_context_class">jta</property>*/

開始用的:

Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Transaction tran=session.beginTransaction();

好多文章裡都說只需在Spring配置<bean id="sessionFactory"...---><property name="hibernateProperties">   中加入 <prop key="hibernate.current_session_context_class">thread</prop>就可以解決,試了沒用.

修改後的:

Session session = this.getHibernateTemplate().getSessionFactory().openSession();

Transaction tran=session.beginTransaction();

......

finally
   {  
    session.close();  
   }

問題解決