Spring-Boot 出现Transaction marked as rollback only异常

最近在开发的过程中遇到了使用Transaction marked as rollback only的问题,了解到报错的原因:

应该是事务被rollback了多次导致的错误。仔细看代码,由于项目中在aop切面、控制层、service分别开启了一次事务,而在service里报错的时候本来在service层已经进行了一次rollback,但是由于在aop环绕切面的时候也开启了事务,捕获到了来自service的异常,于是同一个事务就进行了rollback两次(仅是个人经验的猜测,文章有错请各位大佬指出)
@Transactional配置:
事务隔离级别:TransactionDefinition.ISOLATION_DEFAULT
事务传播行为:TransactionDefinition.PROPAGATION_REQUIRED

解决方案

在org.springframework.transaction.support.AbstractPlatformTransactionManager 中有个叫
isGlobalRollbackOnParticipationFailure的参数,默认是true.
源码中说明:

Switch this to “false” to let the transaction originator make the rollback decision. If a participating transaction fails with an exception, the caller can still decide to continue with a different path within the transaction. However, note that this will only work as long as all participating resources are capable of continuing towards a transaction commit even after a data access failure: This is generally not the case for a Hibernate Session, for example; neither is it for a sequence of JDBC insert/update/delete operations.

大意是:如果isGlobalRollbackOnParticipationFailure为false,则会让主事务决定回滚,如果当遇到exception加入事务失败时,调用者能继续在事务内决定是回滚还是继续。然而,要注意是那样做仅仅适用于在数据访问失败的情况下且只要所有操作事务能提交。

xml

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
  <property name="globalRollbackOnParticipationFailure" value="false" />
 </bean>

spring-boot

@Configuration
@Lazy
@MapperScan("cn.blockchain.core.mapper")
@EnableTransactionManagement(order = 8)
public class TransactionConfig {
    @Bean
    public PlatformTransactionManager txManager(com.alibaba.druid.pool.DruidDataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        dataSourceTransactionManager.setGlobalRollbackOnParticipationFailure(false);
        return dataSourceTransactionManager;
    }
}

参考:

https://blog.csdn.net/zhanghongzheng3213/article/details/50884913
https://blog.csdn.net/bao19901210/article/details/41724355
http://enterkey.tistory.com/320?category=612866

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值