Java JPA REQUIRES_NEW 事务何时提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22348539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:07:11  来源:igfitidea点击:

When exactly does JPA REQUIRES_NEW transaction commit

javaspringhibernatejakarta-eejpa

提问by Ahmad Y. Saleh

In a spring container, with the code below:

在 spring 容器中,代码如下:

public class A {

    @Transactional
    public void m1() {
        ...
        b.m2(); // call in a new transaction
        ...
    }

}

public class B {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void m2() {
        ...
    }

}

when exactly the transaction created for m2()is committed?once m2()invocation ends, or once m1()invocation ends?

何时m2()提交为其创建的事务?一旦m2()调用结束,或者一旦m1()调用结束?

When does @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) commit?answers it for EJB, but it doesn't seem to be the same behavior for JPA.

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 什么时候提交?为 EJB 回答它,但它似乎与 JPA 的行为不同。

I debugged it and I can only see the effect of m2()on DB after m1()ends, but that seems odd to me, am I missing something here?

我调试了它,我只能看到结束m2()后对 DB的影响m1(),但这对我来说似乎很奇怪,我在这里遗漏了什么吗?

UPDATE:

更新:

I was passing the entity I retrieved in m1()to m2()and updating it from there. So, actually merging the entity in m2()solves this and Mik378answer is correct.

我正在传递我检索m1()到的实体m2()并从那里更新它。所以,实际上合并实体m2()解决了这个问题,Mik378 的答案是正确的。

采纳答案by Mik378

From here:

这里

Whether you're using the Spring Framework or EJB, use of the REQUIRES_NEW transaction attribute can have negative results and lead to corrupt and inconsistent data.
The REQUIRES_NEW transaction attribute always starts a new transaction when the method is started, whether or not an existing transaction is present.

无论您使用的是 Spring Framework 还是 EJB,使用 REQUIRES_NEW 事务属性都会产生负面结果并导致数据损坏和不一致。
REQUIRES_NEW 事务属性总是在方法启动时启动一个新事务,无论是否存在现有事务。

REQUIRES_NEWstarts a new transaction even if an existing transaction exist in the context.

REQUIRES_NEW即使上下文中存在现有事务,也会启动新事务。

So the short answer is: once m2()invocation ends

所以简短的回答是:一旦m2()调用结束