处理异常后的Spring嵌套事务​​回滚

时间:2018-01-26 13:22:08

标签: java spring transactions nested-transactions

我有一个@Service类,其中@Transactional方法在另一个服务上调用另一个@Transactional方法。这样的事情:

@Service
public class AService {
  @Autowired
  BService b;
  @Autowired
  ARepository aRepo;

  @Transactional
  public void methodOne(){
    try{
      b.methodTwo();
    }catch(RuntimeException e){}
    aRepo.save(new A());
  }

} 

@Service
public class BService{

    @Transactional
    public void methodTwo(){
      if(true)
        throw new RuntimeException();
    }

}

我希望A实体将是插入的,但是如果任何嵌套的事务抛出异常插入将拒绝,即使这个异常也在AService.methodOne()处理。

我可以使用methodTwo()注释@Transactional(propagation = Propagation.REQUIRES_NEW)。但它会超过性能。

1 个答案:

答案 0 :(得分:0)

如果您不希望在methodOne发生异常后从methodTwo回滚您的交易,则可以使用methodOne添加注释@Transactional(noRollbackFor = {RuntimeException.class})。但是请注意,这有点滑,如果你真的想这样做,请三思而后行。