启动类添加 @EnableTransactionManagement

    service层添加 Transactional

    注意,Transactional 默认只对 uncheck异常进行回滚,比如runtimeException
    踩坑

    1. @Transactional
    2. @Service
    3. public class CompanyServiceService implements CompanyService {
    4. @Autowired
    5. private CompanyMapper companyMapper;
    6. @Autowired
    7. private CompanyBackInfoMapper companyBackInfo;
    8. @Override
    9. public int CompanyInsert(Company company, CompanyBackInfo[] companyBackInfos) throws Exception {
    10. company.setDelete(0);
    11. int i = companyMapper.insertSelective(company);
    12. for (CompanyBackInfo e: companyBackInfos){
    13. e.setDelete(0);
    14. e.setCompanyId(String.valueOf(i));
    15. }
    16. int i1 = companyBackInfo.bulkInsert(companyBackInfos);
    17. throw new BusinessException(112,"shibai"); // 能回滚
    18. throw new Exception("shibai"); // 不能回滚,上面的插入依然执行
    19. }

    BusinessException

    1. public class BusinessException extends RuntimeException {
    2. /**
    3. * 提示编码
    4. */
    5. private final int code;
    6. /**
    7. * 后端提示语
    8. */
    9. private final String msg;
    10. public BusinessException(int code, String msg) {
    11. super(msg);
    12. this.code = code;
    13. this.msg = msg;
    14. }
    15. public BusinessException(ResponseCodeInterface responseCodeInterface) {
    16. this(responseCodeInterface.getCode(),responseCodeInterface.getMsg());
    17. }
    18. public int getCode() {
    19. return code;
    20. }
    21. public String getMsg() {
    22. return msg;
    23. }
    24. }