【问题标题】:Spring boot jpa transaction cannot insert on exceptionSpring boot jpa事务无法插入异常
【发布时间】:2021-10-03 19:40:17
【问题描述】:

我有下面显示的代码,当spring jpa事务中发生异常时,我无法插入错误表。捕获方法 insertInTwoTables 中引发的异常,我想在错误表中插入一些数据。请帮忙。


public class MyClass {

    @Transactional(rollbackFor = Exception.class)
    public void createSomething() {
        try {
            insertInTwoTables();
            // Exception occurs in insertInTwoTables, I want to rollback this method 
               insertInTwoTables updates
        } catch (Exception e) {
            // Since error has occurred I want to insert this information
            // into a error table

            errorInsert();

        }
    }

    @Transactional
    public void insertInTwoTables() {
  }

    @Transactional
    public void errorInsert() {
  }

}

【问题讨论】:

  • 是什么阻止你将它插入到错误表中?

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


【解决方案1】:

在这种情况下,我发现将 errorInsert 放入另一个可以用 spring 注入的类中是成功的。确保此方法的事务注释设置为 REQUIRES_NEW,这样就可以避免任何可能导致操作事务失败的事情,因为 errorInsert 将获得它自己的新事务。

这是我发现的一个涉及错误的页面,需要新的以获得额外的背景。

https://www.netsurfingzone.com/spring/transactional-required-vs-requires_new-example-in-spring-boot/

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 2018-02-04
    • 2023-03-20
    • 2015-06-18
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多