@Transactional (noRollbackFor=RuntimeException.class) does not prevent rollback on RuntimeException

前端 未结 1 804
有刺的猬
有刺的猬 2020-12-17 18:40
@Transactional (noRollbackFor=RuntimeException.class)
public void methodA (Entity e){
   service.methodB(e);
}

---service method below---



        
相关标签:
1条回答
  • 2020-12-17 19:08

    Once an exception is caught, the Hibernate Session should be discarded and the transaction should be rolled back:

    If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

    So, noRollbackFor applies to your Service and DAO layer that might throw an exception. Let's say you have a gatewayService that write to a Database through a Hibernate DAO and also sends an email through an emailService. If the emailService throws a SendMailFailureException you can instruct the gatewayService not to roll back when it will catch this exception:

    @Transactional(noRollbackFor=SendMailFailureException.class)
    public void saveAndSend(Entity e){
       dao.save(e);
       emailService.send(new Email(e));
    }
    
    0 讨论(0)
提交回复
热议问题