事务手动回滚

Posted z360519549

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事务手动回滚相关的知识,希望对你有一定的参考价值。

    @Override
    public BaseResponse transferStuPlan(GxyPlanTeacherStudentEntity teacherStudentEntity) {

      
        boolean  stuIHaveJob = false;
        List<GxyPlanTeacherStudentEntity> deleteStu = new ArrayList<>();
        for(String stuId:teacherStudentEntity.getStuIds()){
            GxyPlanTeacherStudentEntity teacherStudentDto = planTeacherStudentMapper.selectPlanIdAndStuId(teacherStudentEntity.getPlanId(),stuId,teacherStudentEntity.getSnowFlakeId());
         
                Integer countReport = reportService.countReport(reportEntity);
                if(countReport != null && countReport>0){
                    stuIHaveJob = true;
                    break;
                }

                planTeacherStudentMapper.delete(new QueryWrapper<GxyPlanTeacherStudentDto>().eq("plan_teacher_student_id",teacherStudentDto.getPlanTeacherStudentId()).eq("snow_flake_id",teacherStudentEntity.getSnowFlakeId()));
                deleteStu.add(teacherStudentDto);
           
        }

        if(stuIHaveJob){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if(teacherStudentEntity.getStuIds().size()>1){
                return BaseResponse.error("无法删除");
            }
        }else{
            updatePlanIdIntoNewPlan(deleteStu,teacherStudentEntity.getNewPlanId(),teacherStudentEntity.getSnowFlakeId());
        }
        return BaseResponse.ok();
    }
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();   手动回滚。
stuIHaveJob 为true 时,上面的 planTeacherStudentMapper.delete 会回滚。
当 stuIHaveJob 为false 时,上面的 planTeacherStudentMapper.delete 不会回滚,继续执行 updatePlanIdIntoNewPlan。(当此方法中有异常时,也会回滚)

以上是关于事务手动回滚的主要内容,如果未能解决你的问题,请参考以下文章

浅谈Spring中的事务回滚

事务场景中,抛出异常被catch后,如果需要回滚,一定要手动回滚事务

关于项目中遇到的问题-- trycatch 手动回滚事务

spring全注解事务管理中怎么手动回滚事物

mybatis 手动/自动触发事务回滚

SpringBoot事务注解@Transactional 事物回滚手动回滚事物