gpt4 book ai didi

java - @Transactional 注解的方法是否等待 Spring 中的成功提交?

转载 作者:行者123 更新时间:2023-11-30 02:54:17 27 4
gpt4 key购买 nike

在Spring中使用@Transactional注解方法时,注解方法的返回是否与底层数据库事务的成功提交同步?

(这是假设事务实际上会在返回后提交,但根据所选的传播方法,情况可能并非如此。)

如果等待提交不是默认行为,是否有任何方法可以通过配置或其他方式启用它?

我的问题的动机是我想实现一个可靠的“存储和转发”类型端点,它仅在调用的效果提交后才返回响应给客户端稳定的存储。这对于 @Transactional 是否可行?

最佳答案

简短的回答是否定的:该方法不会等待提交。

实际发生的情况取决于两个因素:

  • 调用该方法之前是否存在事务?
  • 使用什么交易传播?

如果没有事务预先存在,则在调用该方法之前会创建一个新事务,并且如果它没有被标记为仅回滚,Spring会尝试在该方法返回后立即提交它 - 在这种情况下,即使该方法不等待提交,提交立即执行。

由于嵌套调用,当物理事务已经存在时调用事务注释方法时,事情会变得更加困难

摘自 Spring 引用手册:

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit

PROPAGATION_REQUIRES_NEW, in contrast to PROPAGATION_REQUIRED, uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status.

PROPAGATION_NESTED uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back.

这意味着除了 PROPAGATION_REQUIRES_NEW 之外,在包含事务结束之前不会尝试提交。

换句话说,如果您希望在事务注释方法结束后立即发生提交,则必须将传播设置为 PROPAGATION_REQUIRES_NEW :@Transactional(propagation=Propagation.REQUIRES_NEW)

关于java - @Transactional 注解的方法是否等待 Spring 中的成功提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37712444/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com