springboot中怎么做到设计到多个表的数据回滚

在实际开发中我们经常会遇到一种问题,就是前端给我们传过来一条数据,这一条数据需要同时插入多个表中,其中如果涉及到事务的回滚应该怎么办。
实际情景如下:
前端传来一条数据,共有10个字段。
前五个字段我们要存在a表中,后五个字段我们要存在b表中。
结果为a表的数据存成功了,b表的数据未成功存入,这时候我们应该是b表数据回滚,a表数据也回滚,那么我们应该怎么实现这种方式呢?
1.事务回滚
启动类加上@EnableTransactionManagement注解,开启事务支持(其实默认是开启的)。
@Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。
示例代码

	@Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCarDealer(DtoCarDealerDetail detail,String userId) throws Exception {
        try{
            if (detail == null) {
                throw new Exception("数据为空!");
            }
            //添加信息并返回id
            String id = customerDisposerService.addCarDealerDetail();
            if(id == null){
                throw new Exception("添加失败!");
            }
            detail.setDisposerID(id);
            //表二添加信息
            boolean flag = customerDisposeritemService.addCarDealerDetail(detail,userId);
            if(!flag){
                throw new Exception("信息添加失败!");
            }
            //表三添加信息
            boolean annex = customerAnnexService.addAnnex();
            if(!annex){
                throw new Exception("信息添加失败!");
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
            log.error(String.format("新建基本信息失败, 原因:%s %n %s", e.getMessage(), Arrays.toString(e.getStackTrace())));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return false;
    }

如果三个表中有一个表添加失败返回false或者产生异常,都会产生事务回滚,将之前添加或者修改的数据进行回滚。

这里需要特别声明一点
正常情况下加注解@Transactional和try catch捕获异常会让注解失效
解决办法就是在catch语句块中添加TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

发布了12 篇原创文章 · 获赞 1 · 访问量 1052

猜你喜欢

转载自blog.csdn.net/Genjicoo/article/details/104288568