启动类添加 @EnableTransactionManagement
service层添加 Transactional
注意,Transactional 默认只对 uncheck异常进行回滚,比如runtimeException
踩坑
@Transactional
@Service
public class CompanyServiceService implements CompanyService {
@Autowired
private CompanyMapper companyMapper;
@Autowired
private CompanyBackInfoMapper companyBackInfo;
@Override
public int CompanyInsert(Company company, CompanyBackInfo[] companyBackInfos) throws Exception {
company.setDelete(0);
int i = companyMapper.insertSelective(company);
for (CompanyBackInfo e: companyBackInfos){
e.setDelete(0);
e.setCompanyId(String.valueOf(i));
}
int i1 = companyBackInfo.bulkInsert(companyBackInfos);
throw new BusinessException(112,"shibai"); // 能回滚
throw new Exception("shibai"); // 不能回滚,上面的插入依然执行
}
BusinessException
public class BusinessException extends RuntimeException {
/**
* 提示编码
*/
private final int code;
/**
* 后端提示语
*/
private final String msg;
public BusinessException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public BusinessException(ResponseCodeInterface responseCodeInterface) {
this(responseCodeInterface.getCode(),responseCodeInterface.getMsg());
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}