先看代码
@Transactional(rollbackFor = Exception.class)
@Override
public void delete(Integer id) {
try {
// 判断 id 是否存在,存在继续;不存在,输出不存在,报错结束
deptMapper.deleteById(id);
// 根据部门ID删除该部门的员工信息
empMapper.deleteByDeptId(id);
} catch (Exception e) {
throw new RuntimeException(e);
} finally { // 事物传播行为
DeptLog deptLog = new DeptLog();
deptLog.setCreateTime(LocalDateTime.now());
deptLog.setDescription("解散部门,删除的部分 " + id );
deptLogService.insert(deptLog);
}
}
这里的 finally 的代码含义: 删除部门的操作,写入日志。
写入日志操作也是 事物传播行为最常见的操作之一。
deptLogService.insert(deptLog);
对应的代码如下,
@Service
public class DeptLogServiceImpl implements DeptLogService {
@Autowired
private DeptLogMapper deptLogMapper;
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void insert(DeptLog deptLog) {
deptLogMapper.insert(deptLog);
}
}
这里的
@Transactional(propagation = Propagation.REQUIRES_NEW)
没有用默认值,而是定义了 propagation 。
默认值,会和 delete 操作共用一个事物;如果遇到 delete 错误的异常,log 不会被记录 ——
会和 delete 操作一起回滚。
之后,通过
propagation = Propagation.REQUIRES_NEW
生成一个新的「事物」,才能确保日志记录的独立性。
⚠️ : 通过 debug 需要调试的可以私信联系提供全部代码。