spring 事务传播验证

package com.example.flyway.service;

import com.example.flyway.bean.User;
import com.example.flyway.mapper.UserMapper;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class AService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    BService bService;
    
    @Transactional
    public void test1(){
        userMapper.insert1();
        userMapper.insert2();
        bService.test2();
    }
	@Transactional
    public void test2(){
        userMapper.insert1();
        userMapper.insert2();
        bService.test1();
        int i = 1/ 0;
    }
}

@Service
public class BService {

    @Autowired
    UserMapper userMapper;
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void test1(){
        userMapper.insert3();
        userMapper.insert4();
    }

    @Transactional
    public void test2(){
        userMapper.insert3();
        int i = 1/0;
        userMapper.insert4();
    }
}

1、test2没有加事务
表123全部回滚
2、Propagation.REQUIRED 默认 ,如果存在事务则在该事务中运行,如果不存在事务,则开启一个事务
表123全部回滚
3、Propagation.SUPPORTS 当前方法不需要事务上下文,如果存在事务则在该事务中运行
执行test1方法,表123全部回滚
单独执行BService.test2方法,表3不会回滚,相当于没有事务
4、Propagation.MANDATORY 表示必须在事务中执行,否则抛出异常
执行test1方法,表123全部回滚
单独执行BService.test2方法,抛出IllegalTransactionStateException异常,无法进入test2方法
5、Propagation.REQUIRES_NEW 新建事务,如果当前存在事务,把当前事务挂起。
执行test2方法,表12回滚,表34插入成功
6、Propagation.NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
7、Propagation.NEVER 以非事务方式执行,如果当前存在事务,则抛出异常
8、Propagation.NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。
执行test1 表123全部回滚
执行test2 表123全部回滚
外部事务回滚会引起内部事务回滚,内部事务回滚同时外部事务回滚

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值