JAVA@Transactional常用失效场景

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public boolean create() {
        create1();
        create2();
        return true;
    }
public void create1() {
Student student = new Student();
student.setName("事务1");
//不能为空
student.setGender(1);
int result = studentMapper.insert(student);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}

public void create2() {
Student student = new Student();
student.setName("事务2");
student.setGender(1);
studentMapper.insert(student);
Student student2 = new Student();
student2.setName("事务3");
int result = studentMapper.insert(student2);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
 

以上事务生效。在create()方法上添加事务,create2()因为gender为空产生报错,促使整个create()方法回滚,整体可以理解为是长事务;

 

@Override
public boolean create() {
create1();
create2();
return true;
}

@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public void create1() {
Student student = new Student();
student.setName("事务1");
//不能为空
student.setGender(1);
int result = studentMapper.insert(student);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public void create2() {
Student student = new Student();
student.setName("事务2");
student.setGender(1);
studentMapper.insert(student);
Student student2 = new Student();
student2.setName("事务3");
int result = studentMapper.insert(student2);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}

以上事务触发不生效规则——同一个类中里层方法(create1(),create2())添加@Transactional注解不生效,需要在外层方法(create())添加@Transactional注解才会生效。以上两个方法create1和create2均加有 @Transactional注解,但是这种方式不会生效,create1会执行成功并提交到数据库,create2的事务2会成功插入数据库,但是事务3不会插入数据库,从而引发了数据的不一致性。

 

    @Override
    public boolean create() {
        studentService2.create1();
        studentService2.create2();
        return true;
    }
StudentService:

@Transactional(rollbackFor = {RuntimeException.class, Error.class}) public void create1() { Student student = new Student(); student.setName("事务1"); //不能为空 student.setGender(1); int result = studentMapper.insert(student); if (result != 1) { throw new RuntimeException("新增失败"); } } @Transactional(rollbackFor = {RuntimeException.class, Error.class}) public void create2() { Student student = new Student(); student.setName("事务2"); student.setGender(1); studentMapper.insert(student); Student student2 = new Student(); student2.setName("事务3"); int result = studentMapper.insert(student2); if (result != 1) { throw new RuntimeException("新增失败"); } }

此种方式事务生效,事务1能够成功保存到数据库,事务2和事务3因为异常无法保存到数据库。

 

posted @ 2024-07-13 14:15  HexThinking  阅读(3)  评论(0编辑  收藏  举报