春季交易:requires_new行为

时间:2014-04-08 04:47:13

标签: spring transactions behavior

可能是我误解了Spring Requires_new的行为。这是我的代码:

@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抛出异常时,我认为innerMethod1仍然能够提交。但所有外部和内部事务都回滚。我错在哪里?当innerMethod2回滚时,如何提交innerMethod1?

1 个答案:

答案 0 :(得分:4)

虽然您已正确理解了Propagation.REQUIRES_NEW的行为,但您偶然发现了一个关于Spring的Transactional行为的常见误解。

为了应用事务语义(即对方法的注释产生任何影响),需要从类外部调用该方法。从类内部调用使用transactional注释的方法对事务处理完全没有影响(因为Spring生成的包含事务代码的代理类没有起作用)。

在您的示例中,innerMethod2可能使用@Transactional进行注释,但由于它是从outterMethod调用的,因此未处理注释。

查看Spring文档的this部分

相关问题