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 @   HexThinking  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示