春季交易:require_new行为 [英] Spring transaction: requires_new beharivour

查看:100
本文介绍了春季交易:require_new行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是我误会了Spring Requires_new行为.这是我的代码:

May be I am misunderstand Spring Requires_new behavior. Here is my code:

@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
public void outterMethod() throws Exception{
    innerMethod1();
    innerMethod2();         
}
@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW)
public void innerMethod1() throws Exception{
    testService.insert(new Testbo("test-2", new Date()));
}

@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW)
public void innerMethod2() throws Exception{
    testService.insert(new Testbo("test-2", new Date()));
    throw new Exception();
}

当innnerMethod2引发Exception时,我认为innerMethod1仍然可以提交.但是所有外部和内部事务都会回滚.我这是怎么了内部方法2回滚时如何提交内部方法1?

When the innnerMethod2 throws Exception, I thought that innerMethod1 still able to commit. But the all the outer and inner transactions rollback. What am I wrong here? How can I do to commit innerMethod1 when innerMethod2 rollback?

推荐答案

尽管您已经正确理解了Propagation.REQUIRES_NEW的行为,但是您还是偶然发现了一个关于Spring事务性行为的常见误解.

Although you have correctly understood the behavior of Propagation.REQUIRES_NEW, you have stumbled upon a common misconception about Spring 's Transactional behavior.

为了应用事务语义(即,方法的注释生效),需要从类外部调用该方法.从类内部调用带有事务性注释的方法绝对不会影响事务处理(因为包含事务代码的Spring生成的代理类不会起作用).

In order for the transactional semantics to be applied (that is for the annotation of the method to have any effect), the method needs to be called from outside the class. Calling a method annotated with transactional from inside the class has absolutely no effect on the transactional processing (because the Spring generated proxy class that contains the transactional code does not come into play).

在您的示例中,innerMethod2可能带有@Transactional注释,但由于是从outterMethod调用的,因此注释未得到处理.

In your example innerMethod2 maybe annotated with @Transactional but since it is called from outterMethod, the annotation is not being processed.

签出 Spring文档的这部分

这篇关于春季交易:require_new行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆