如何解决Spring Data JPA避免UnexpectedRollbackException
我有一个包含Spring Boot(2.3.3.RELEASE),Spring Data JPA(2.3.3.RELEASE)和Hibernate(5.4.20)的项目。
我正在尝试从DataIntegrityViolationException中恢复,该异常在尝试保存违反数据库约束的Entity之后发生。例如:
@Transactional
public void doSomething() {
// save some data into the database
try {
User user = new User();
user.setName("test");
// This method fails because of a constraint
userService.save(user);
} catch (DataIntegrityViolationException e) {
LOGGER.info("Exception caught. Trying to recover...",e);
}
// continue doing other things
}
当我捕获到异常时,doSomething
方法结束时,我希望Spring会提交更改。但是,Spring抛出以下异常:
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
据我所知,当发生完整性违规时,Hibernate将该事务标记为仅回滚,因此Spring会中止该事务。
我试图通过在@Transactional
方法中添加具有noRollbackFor
属性的userService.save
注释来避免这种行为,但是在这种情况下它没有用。
我可以为添加userService.save
批注的@Transactional(propagation = Propagation.REQUIRES_NEW)
方法创建一个新事务。但是,我想将所有更改保留在同一笔交易中。
使用纯JDBC,从DataIntegrityViolationException
中恢复并提交更改完全没有问题。 ¿有什么办法可以用Hibernate改变这种行为?
我已经在Github中创建了一个演示项目来检查此行为:https://github.com/wearearima/hibernate-rollback
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。