事物传播行为,Spring Boot 3 的处理

 先看代码

    @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 需要调试的可以私信联系提供全部代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值