一。事物回顾
事务管理一般用在增删改方法上
在删除数据过程中,可能会出现异常,导致数据删除出现问题,因此采用事物回滚
二,事物进阶
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);
}
}