spring事务失效的一个情况

service调用同类方法会发生事务失效的情况,代码如下

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassService classService;

    public void addStudent() {
        test();
    }

    @Transactional(rollbackFor = Exception.class)
    public void test() {
        Student student = new Student(2, "qiao", "man", 20, 30);
        Student student2 = new Student(2, "qiao", "man", 20, 30);
        studentMapper.add(student);
        studentMapper.add(student2);
    }

}

addStudent方法调用test方法会发生test方法事务失效的情况,

解决办法

  1. 在addStudent方法上也加上事务
  2. 使用spring框架提供的AopContent类去生成一个本类的代理去进行事务植入。
    使用方法如下
    加入aop包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

设置exposeProxy为true,在spring boot启动类上加入
@EnableAspectJAutoProxy(exposeProxy = true)

使用AopContext.currentProxy()进行service代理进行aop植入

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassService classService;

    public void addStudent() {
    
        ((StudentService)AopContext.currentProxy()).test();
    
        
    }

    @Transactional(rollbackFor = Exception.class)
    public void test() {
        Student student = new Student(2, "qiao", "man", 20, 30);
        Student student2 = new Student(2, "qiao", "man", 20, 30);
        studentMapper.add(student);
        studentMapper.add(student2);
    }

}

这样事务就不会失效了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值