java @Transactional (noRollbackFor=RuntimeException.class) 不会阻止 RuntimeException 的回滚

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27849968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:31:02  来源:igfitidea点击:

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

javaspringhibernatejpatransactions

提问by ThermalEagle

@Transactional (noRollbackFor=RuntimeException.class)
public void methodA (Entity e){
   service.methodB(e);
}

---service method below---

---以下服务方式---

@Transactional (propagation=Propagation.REQUIRES_NEW, noRollbackFor=RuntimeException.class)
public void methodB (Entity e){
   dao.insert(e);
}

When dao.insert(e)in methodB()causes a primary key violation and throws a ConstraintViolationException, which is a subclass of RuntimeException, I would expect the transaction to still commit because of the noRollbackForproperty I used. But I observed that the outer transaction (on methodA) is still being rolled back by the HibernateTransactionManagerwith the message

dao.insert(e)inmethodB()导致主键违规并抛出 a ConstraintViolationException(它是 的子类)时RuntimeException,由于noRollbackFor我使用的属性,我希望事务仍然提交。但我观察到外部事务 (on methodA) 仍然被HibernateTransactionManager消息回滚

org.springframework.transaction.UnexpectedRollback Exception: Transaction rolled back because it has been marked as rollback-only

org.springframework.transaction.UnexpectedRollback 异常:事务回滚,因为它已被标记为仅回滚

I've found similar questions reported but not exactly this one.

我发现报告了类似的问题,但不完全是这个问题。

回答by Vlad Mihalcea

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

一旦捕获到异常,就应该丢弃Hibernate Session并回滚事务:

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.

如果会话抛出异常,则必须回滚事务并丢弃会话。异常发生后,Session的内部状态可能与数据库不一致。

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

因此,noRollbackFor适用于可能引发异常的 Service 和 DAO 层。假设您有一个gatewayService,它通过 Hibernate DAO 写入数据库,并通过emailService发送电子邮件。如果 emailService 抛出 aSendMailFailureException您可以指示gatewayService在捕获此异常时不要回滚:

@Transactional(noRollbackFor=SendMailFailureException.class)
public void saveAndSend(Entity e){
   dao.save(e);
   emailService.send(new Email(e));
}