【问题标题】:Spring JPA: Unexpected rollback exception hides the actual exception I need to handleSpring JPA:意外回滚异常隐藏了我需要处理的实际异常
【发布时间】:2021-05-31 13:20:30
【问题描述】:

我正在 Spring Boot 中尝试使用 @transactional。我已经编写了一个包含多个表插入的服务,如果有任何异常,我希望整个事情都回滚。
这工作正常,但不是抛出导致回滚的实际异常,我得到Unexpected Rollback Exception

@transactional
public void insertIntoTables(){
    repositoryone.save(new Table1());
    repositorytwo.save(new Table2()); //expecting data integrity violation exception on this line
}

上面的代码不是抛出DataIntegrityViolationException,而是抛出Unexpected Rollback Exception。我当然希望回滚发生,只是想避免异常,以便我可以使用实际的。
如何获取实际异常以进行处理?

【问题讨论】:

  • 你在哪里扔DataIntegrityViolationException?如果你想抛出它而不是 UnexpectedRollbackException,那么用 try-catch 块包围 save 方法,捕获 UnexpectedRollbackException,然后抛出你想抛出的异常。
  • 那是因为在提交期间发生了异常。如果您想在提交之前触发约束检查,请执行saveAndFlush(假设您正在为您的存储库扩展JpaRepository)或直接在EntityManager 上调用flush。 Thatt 将在提交之前触发与数据库的状态同步,并为您提供另一个 DataAccessException

标签: java mysql spring spring-data-jpa spring-transactions


【解决方案1】:

即使我以前也遇到过类似的问题。我通过添加回滚来处理它。以下是我的处理方式。

  1. 导入org.springframework.transaction.annotation.Transactional
  2. 然后我在服务方法上方使用@Transactional(rollbackFor = Exception.class) 而不是@Transactional

这将处理任何运行时异常。因此,应该向用户显示 DataIntegrityViolationException。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 2020-08-03
    • 1970-01-01
    • 2022-08-13
    • 2015-05-28
    • 1970-01-01
    • 2012-12-02
    • 2012-04-09
    相关资源
    最近更新 更多