@Transactional (noRollbackFor=RuntimeException.class) 不会阻止 RuntimeException 的回滚 [英] @Transactional (noRollbackFor=RuntimeException.class) does not prevent rollback on RuntimeException

查看:16
本文介绍了@Transactional (noRollbackFor=RuntimeException.class) 不会阻止 RuntimeException 的回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

methodB() 中的 dao.insert(e) 导致主键违规并抛出 ConstraintViolationException,它是RuntimeException,我希望事务仍然提交,因为我使用了 noRollbackFor 属性.但是我观察到外部事务(在 methodA 上)仍然被 HibernateTransactionManager 与消息回滚

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 noRollbackFor property I used. But I observed that the outer transaction (on methodA) is still being rolled back by the HibernateTransactionManager with the message

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

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

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

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

推荐答案

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

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

如果Session抛出异常,事务必须被roll返回并丢弃会话.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.

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

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

这篇关于@Transactional (noRollbackFor=RuntimeException.class) 不会阻止 RuntimeException 的回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆