database - Spring Propagation.REQUIRES_NEW 嵌套在 Propagation.NESTED 时的行为

标签 database spring postgresql spring-transactions

我有这样的代码

@Transactional(propagation = Propagation.NESTED)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class C1 {
...
   public void xxx() {
      try {
         obj.someMethod();
      } catch (Exception e) {
         C2.yyy();
      }
   }
}

public class C2 {
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
    public void yyy() {
        ...
    }
}

我的假设是,当 obj.someMethod(); 抛出违反约束的异常时,C2.yyy() 应该仍然能够将内容保存到数据库中。

但是我看到的是,当 C2.yyy() 被称为 Postgres 报告时

ERROR: current transaction is aborted, commands ignored until end of transaction block

为什么要这样做?毕竟 C2.yyy() 应该在不同的事务中运行,该事务应该不受调用代码中发生的状态的影响。不?

更新

这里是我发现的进一步调试 - 让我们假设调用堆栈是这样的

@Transactional(readOnly = false, propagation = Propagation.NESTED)
b1.m1()
       @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
       b2.m2()
              b3.m3()
                      b4.m4()

我的假设是,由于 b2.m2() 上的注解,m4() 中的数据库代码将在新事务中执行。但似乎TransactionAspectSupport.java中的代码只查看当前方法上的事务注解,而不查看堆栈上的事务注解。当它在 m4() 上找不到任何 @transactional 时,它假定需要。这不是不正确吗?

最佳答案

如此处 DatabaseError: current transaction is aborted, commands ignored until end of transaction block 所回答:“当查询产生错误并且您尝试运行另一个查询而不先回滚事务时,这就是 postgres 所做的”。

这意味着您的“obj”应该在其自己的事务中运行并在出现异常时回滚。

关于更新中的问题:REQUIRES_NEW 总是创建一个新事务,它既是 documented 又是经过测试的。

关于database - Spring Propagation.REQUIRES_NEW 嵌套在 Propagation.NESTED 时的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008731/

相关文章:

postgresql - UPSERT Postgres 9.5

c++ - QSqlDatabase/QSqlQuery 终止正在运行的查询?

Postgresql:获取具有相似列值的记录

mysql - 从 MySQL 中获取对应于某种模式的数据

SQL查询: select the last record where a value went below a threshold

python - 如何从 (.db) 文件读取 python 变量并为其赋值

java - Spring MVC 缺少静态资源

java - 从 com.mchange.v2.async.ThreadPoolAsynchronousRunner 停止 tomcat 7 时发出警告

javascript - 迭代和转换数组中的对象

java - 为什么我的中间存储库接口(interface)从 Spring Data JPA 1.4.x 升级到更新版本(例如 1.7.1)后会出现问题?