代码之家  ›  专栏  ›  技术社区  ›  Thien Dinh

春季交易:需要新建

  •  2
  • Thien Dinh  · 技术社区  · 10 年前

    可能是我误解了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();
    }
    

    当innerMethod2抛出异常时,我认为innerMethod1仍然能够提交。但所有外部和内部事务都会回滚。我怎么了?当innerMethod2回滚时,如何提交innerMethod1?

    1 回复  |  直到 10 年前
        1
  •  4
  •   geoand    9 年前

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

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

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

    退房 this Spring文档的一部分