事务 管理

 一。事物回顾

事务管理一般用在增删改方法上

在删除数据过程中,可能会出现异常,导致数据删除出现问题,因此采用事物回滚

 二,事物进阶

2.1 RollbackFor

默认情况下,只有出现RuntimeExpection才回滚异常,RollbackFor可以回滚所有异常

2.2propagation

事物传播行为:REQUIRED:大部分情况都是用该传播行为

REQUIRES_NEW:当我们不希望事物相互影响时,可以使用,比如下订单前需要记录日志,不论订单是否保存成功,都要保证日志记录成功

示例代码

   try {
        deptMapper.deleteById(id);
        int i=1/0;
//    if (true){
//        throw  new Exception("出错了");
//    }

        empMapper.deleteByDeptId(id);
    } finally {
        DeptLog deptLog =new DeptLog();

        deptLog.setCreateTime(LocalDateTime.now());
        deptLog.setDescription("删除部门"+id);
        deptLogService.insert(deptLog);

    }

package com.example.tiaswebmanagement.service.impl;

import com.example.tiaswebmanagement.mapper.DeptLogMapper;
import com.example.tiaswebmanagement.mapper.DeptMapper;
import com.example.tiaswebmanagement.pojo.DeptLog;
import com.example.tiaswebmanagement.service.DeptLogservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class DeptLogserviceImpl implements DeptLogservice {
    @Autowired
    private DeptLogMapper deptLogMapper;
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void insert(DeptLog deptLog){
        deptLogMapper.insert(deptLog);
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值