String事务实现在循环体中回滚异常提交正常

原理

  1. 需要配合声明式事务@Transactional(rollbackFor = Exception.class)
  2. 通过设置保存点savePoint(编程式事务)

代码如下,模拟批量新增热词的业务,把for循环中偶数次手动失败。

    @Transactional(rollbackFor = Exception.class)
    public Result test() {
        //初始化10个热词
        List<HotWord> hotWordList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            HotWord hotWord = new HotWord();
            hotWord.setName("test"+i);
            hotWordList.add(hotWord);
        }
        int success = 0;
        int fail = 0;
        boolean b = true;
        Object savePoint = null;
        for (HotWord hotWord : hotWordList) {
            try {
                mapper.insertSelective(hotWord);
                b = !b;
                //手动把奇数索引抛异常
                if (b) {
                    fail++;
                    throw new Exception();
                }
                success++;
                //成功则设置savePoint
                savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            } catch (Exception e) {
                e.printStackTrace();
                //捕获异常回滚到上个savePoint
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        return ResultUtil.ok("成功:"+success+" 失败:"+fail);
    }

结果:成功 5 条,失败 5 条。数据库新增的数据有:
String事务实现在循环体中回滚异常提交正常_第1张图片

你可能感兴趣的:(springboot,事务,mysql,spring)