问题
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