2012-08-17 37 views
8

我正在創建JSF應用程序並在其中使用一些休眠的東西。所有我想要做的就是將實體保存到數據庫中,但我不斷收到此異常:org.hibernate.HibernateException:保存無效,沒有活動事務

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

起初,我得到這個異常:

org.hibernate.HibernateException: No CurrentSessionContext configured! 

後來我發現,我需要添加這進入我的休眠配置:

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

這解決了這個問題,但現在上面出現。 我保存實體到數據庫這樣的:

public void create(T entity) { 
    getSessionFactory().getCurrentSession().save(entity); 
} 

我的hibernate.cfg.xml文件看起來是這樣的:

<hibernate-configuration> 
    <session-factory> 
     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
     <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/online_tests_management</property> 
     <property name="hibernate.connection.username">root</property> 
     <property name="hibernate.connection.password">root</property> 
     <property name="hibernate.show_sql">true</property> 
     <property name="hibernate.hbm2ddl.auto">update</property> 
     <property name="hibernate.current_session_context_class">thread</property> 

     <mapping class="com.groupgti.onlinetests.management.db.Service"/> 
    </session-factory> 
</hibernate-configuration> 

我使用:

  • 的Hibernate 4.1.4 .Final
  • JDK 1.6
  • Tomcat 6
  • JSF 2.0
  • PrimeFaces 3.3.1
  • MySql的

是否有人知道可能是問題嗎?

回答

20

你必須調用

public void create(T entity) { 
    Session session=getSessionFactory().getCurrentSession(); 
    Transaction trans=session.beginTransaction(); 
    session.save(entity); 
    trans.commit(); 
} 
+0

謝謝你,工作。 – 2012-08-17 09:41:02

+0

我通過Spring AOP使用Spring HibernateTransactionManager來配置事務。我可以在日誌中看到事務正常啓動,但由於我沒有使用上面的代碼,因此我的保存仍然失敗。這是爲什麼? – 2015-03-17 15:24:45

3

試着改變你的方法如下:

public void create(T entity) { 
    getSessionFactory().getCurrentSession().beginTransaction(); 
    getSessionFactory().getCurrentSession().save(entity); 
    getSessionFactory().getCurrentSession().endTransaction(); 
} 

應該解決您的問題。

3

做這樣的:

public void create(T entity) { 
     org.hibernate.Session ss= getSessionFactory().getCurrentSession(); 
     Transaction tx=ss.beginTransaction(); 
     ss.save(entity); 
     tx.commit();  
    } 

執行異常處理自己的一部分。

2

我想你會發現這樣的事情是更強大的和適當的:

Session session = factory.openSession(); 
Transaction tx = null; 
try { 
    tx = session.beginTransaction(); 

    // Do some work like: 
    //session.load(...); 
    //session.persist(...); 
    //session.save(...); 

    tx.commit(); // Flush happens automatically 
} 
catch (RuntimeException e) { 
    tx.rollback(); 
    throw e; // or display error message 
} 
finally { 
    session.close(); 
} 

你不能「親密」的交易,你可以關閉會話,你可以看到。閱讀this here,它可能對你有用。

+0

應避免使用「openSession」。正確的方法是「getCurrentSession」。 – 2013-01-30 07:47:33

相關問題