为什么Hibernate不支持Spring之外的嵌套事务?

时间:2016-03-15 20:56:02

标签: spring hibernate transactions nested

我正在使用Hibernate4而不是Spring。在我正在开发的应用程序中,我想将每个Add,Update,Delete的记录记录到单独的日志表中。目前,我的代码依次执行两个事务,并且它可以工作,但我真的想将它们包装成一个事务。

我知道Hibernate不支持嵌套事务,只与Spring框架结合使用。我读过关于保存点的内容,但它们并不完全相同。

1 个答案:

答案 0 :(得分:0)

有关JPA和JTA规范的标准中没有任何内容支持嵌套事务。

春天支持你最有可能的意思是@Transactional注释在呼叫hierarchie中的多种方法。在那种情况下,如果没有开始新的交易,那么在那里检查是否存在正在进行的交易。

您可能认为以下情况是嵌套事务。

@Transactional
public void method1(){
    method2(); // method in another class
}

@Transactional(propagation=REQUIRES_NEW)
public void method2(){
    // do something
}

实际上发生的事情简化如下。 transactionManager1 transactionManager2 的类型是 javax.transaction.TransactionManager

// call of method1 intercepted by spring
transactionManager1.begin();
// invocation of method1 
// call of method 2 intercepted by spring (requires new detected)
transactionManager1.suspend();
transactionManager2.begin();
// invocation of method2
// method2 finished
transactionManager2.commit();
transactionManager1.resume();
// method1 finished
transactionManager1.commit();

一句话,一个交易基本上是暂停的。理解这一点很重要。由于transactionManager2的事务可能看不到transactionManager1的更改,具体取决于事务隔离级别。

也许有点背景为什么我知道这一点。我编写了分布式事务管理系统的原型,允许在云环境中透明地执行方法(一个方法在实例上执行,下一个方法可能在其他地方执行)。