the-red-paintings
the-red-paintings

Reputation: 83

Spring nested transaction rollback after handling exception

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.

Upvotes: 8

Views: 5268

Answers (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.

Upvotes: 2

Related Questions