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(); } }
至于这里面的深层含义,我正在琢磨中,到下一篇给大家做详细介绍
还没有评论,来说两句吧...