spring - 如何在 `noRollbackFor` 上设置 `TransactionTemplate` ?

标签 spring spring-boot

鉴于我设置了如下所示的 TransactionTemplate(在现有事务中启动新事务),如何防止父 (@Transactional) 事务在代码内部回滚子事务抛出特定异常?本质上,模拟 @TransactionalnoRollbackFor 参数。

@Transactional
public void foo() {
    bar();
}

private void bar() {
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);

    transactionTemplate.execute(__ -> {
        // ...
    });
}

最佳答案

这对于 TransactionTemplate 来说是不可能的。
TransactionTemplate 不支持回滚规则。
请参阅:https://github.com/spring-projects/spring-framework/issues/25086

This is by design: TransactionTemplate does not support custom rollback rules. Technically TransactionTemplate isn't even aware of TransactionAttribute since that variant is an extended definition only supported by TransactionInterceptor (and therefore also living in the latter's package). The template operates on plain TransactionDefinition and uses fixed rollback behavior for all exceptions thrown from its callbacks, effectively RuntimeExceptions and Errors.

Alternatively, you may use the PlatformTransactionManager directly: Inject it, call getTransaction on it, perform some resource operations, then call commit in a finally block... and handle potential runtime exceptions any way you need to, without calling rollback. You may also selectively handle the outcome, as long as you eventually call commit (or rollback, for that matter) to complete the transaction.

更好地控制回滚内容和失败内容的替代解决方案是使用保存点,请参阅 https://dzone.com/articles/transaction-savepoints-in-spring-jdbc

关于spring - 如何在 `noRollbackFor` 上设置 `TransactionTemplate` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69329687/

相关文章:

java - 带有 Netty4 的 Spring RestTemplate 和 AsyncRestTemplate 永远挂起

java - 错误: Spring 启动数据库错误“org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration”

java - Spring Boot 作为 war 与 jar

java - Spring Boot 2 WebClient响应将JSON转换为HashMap

java - 如何使用 spring 配置异步和同步事件发布者

java - struts到spring迁移消息资源

java - Liquibase Maven : Cannot find changelog location when spring-boot starts

java - 设置Tomcat的Servlet上下文初始化参数

java - Spring JPA CrudRepository Autowired 对象与 Apache Commons Tailer 一起使用时为 null

spring - Jackson 序列化器 Spring Bean