学习笔记--事务管理
概念
具体使用操作
用于有多条数据库操作时,类似的前面新增员工的操作
Spring事务管理-控制事务
通常情况下给方法加这个注解
@Transactional@Overridepublic void save(Emp emp) {//1.保存员工基本信息emp.setCreateTime(LocalDateTime.now());emp.setUpdateTime(LocalDateTime.now());empMapper.insert(emp);// int i = 1/0;//2.保存员工工作经历List<EmpExpr> exprList = emp.getExprList();if(!CollectionUtils.isEmpty(exprList)){//遍历集合,为empId赋值exprList.forEach(empExpr -> {empExpr.setEmpId(emp.getId());});empExprMapper.insertBatch(exprList);}}
事务进阶--rollbackFor
原本的事务管理默认出现运行时异常RuntimeException才会出现回滚
在注解后面加上这个属性可以用于控制出现何种异常时回滚
@Transactional(rollbackFor = Exception.class)@Overridepublic void save(Emp emp) throws Exception {//1.保存员工基本信息emp.setCreateTime(LocalDateTime.now());emp.setUpdateTime(LocalDateTime.now());empMapper.insert(emp);if(true) {throw new Exception("出错了");}//2.保存员工工作经历List<EmpExpr> exprList = emp.getExprList();if(!CollectionUtils.isEmpty(exprList)){//遍历集合,为empId赋值exprList.forEach(empExpr -> {empExpr.setEmpId(emp.getId());});empExprMapper.insertBatch(exprList);}}
事务进阶--propagation
四大特性
@Service
public class EmpLogServiceImpl implements EmpLogService {@Autowiredprivate EmpLogMapper empLogMapper;@Transactional(propagation = Propagation.REQUIRES_NEW)@Overridepublic void insertLog(EmpLog empLog) {empLogMapper.insert(empLog);}
}
四大特性利用新建事务,实现了无论有没有错误都会保存日志