跳至主要內容

[java] org.hibernate.TransactionException: nested transactions not supported

nested transactions not supported,有需要的朋友可以參考下。
最近自己做一個專案。下載了最新的Hibernate包版本:hibernate-release-4.3.4.Final
開始程式碼: package cn.cwnu.jsj.se.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.junit.BeforeClass;import org.junit.Test;import cn.cwnu.jsj.se.bean.product.ProductType;public class ProductTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void runTest() { Configuration cfg = new Configuration().configure(); SessionFactory sf = new Configuration().configure() .buildSessionFactory( new StandardServiceRegistryBuilder().applySettings( cfg.getProperties()).build()); Session s = sf.getCurrentSession(); Transaction ts = s.beginTransaction(); ProductType p = new ProductType(); ts.begin(); s.save(p); ts.commit(); // s.getTransaction().commit(); // s.flush(); // s.close(); } public static void main(String[] args) { new ProductTest().runTest(); }}
一直給我報錯誤Exception in thread “main” org.hibernate.TransactionException:nested transactions not supported
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:154)
at cn.cwnu.jsj.se.test.ProductTest.runTest(ProductTest.java:31)
at cn.cwnu.jsj.se.test.ProductTest.main(ProductTest.java:40)
又查了資料,原來Hibernate根本就不支援Nested Transaction,最新的Hibernate4也是如此。在配置檔案中設定”nestedTransactionAllowed=true”,其實只對JDBC事務起效(如使用Spring的JdbcTemplate)。經過測試,Hibernate框架託管下的Nested Transaction方法(子事務)丟擲異常時,Spring日誌會提示Rolling back transaction to savepoint,不過所謂“回滾”的是使用JDBC操作的內容,如果事務中沒有JDBC操作等於是沒有效果的。子事務操作會被儲存到Hibernate的快取中,並在下一次flush時被提交。
解決方法是去掉
session.beginTransation();
session.getTransaction().commit();

這樣問題就解決了!
程式碼如下: package cn.cwnu.jsj.se.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.junit.BeforeClass;import org.junit.Test;import cn.cwnu.jsj.se.bean.product.ProductType;public class ProductTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void runTest() { Configuration cfg = new Configuration().configure(); SessionFactory sf = new Configuration().configure() .buildSessionFactory( new StandardServiceRegistryBuilder().applySettings( cfg.getProperties()).build()); Session s = sf.getCurrentSession(); s.beginTransaction(); ProductType p = new ProductType(); s.save(p); // ts.commit(); s.getTransaction().commit(); // s.flush(); // s.close(); } public static void main(String[] args) { new ProductTest().runTest(); }}
https://www.itread01.com/p/556055.html

分類:java
由 Compete Themes 設計的 Author 佈景主題