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方法事务失效的情况,
解决办法
- 在addStudent方法上也加上事务
- 使用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);
}
}
这样事务就不会失效了。