Spring nested transaction rollback after handling exception

ε祈祈猫儿з 提交于 2019-12-24 09:45:12

问题


I have a @Service class which has a @Transactional method that calls another @Transactional method on the another service. Something like that:

@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();
    }

}

I expect that A entity will be insert, but if any nested transaction throw exception insert will reject even this exception was handled at AService.methodOne().

I can annotate methodTwo() with @Transactional(propagation = Propagation.REQUIRES_NEW). But it will beat performance.


回答1:


If you don't want to rollback your transaction from methodOne after some exception happens in the methodTwo, you can add annotate methodOne with @Transactional(noRollbackFor = {RuntimeException.class}). But please be aware that this is a bit of slippery slope and think twice if you really want to do it.



来源:https://stackoverflow.com/questions/48462191/spring-nested-transaction-rollback-after-handling-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!