SpringBoot - 事务处理
目录
- 事务介绍
- 引入案例
- 事务进阶
事务介绍
是一组操作的集合,它是一个不可分割的工作单位,这些操作要么同时成功,要么同时失败
Spring 事务管理:
- 注解: @Transactional
- 位置:业务层的方法上、类上、接口上
- 作用:将当前方法交给spring 进行事务管理,方法执行前,开始事务。成功执行完毕,提交事务,出现异常,回滚事务
引入案例
package com.chuangzhou.serivce.impl;
import com.chuangzhou.mapper.DeptMapper;
import com.chuangzhou.mapper.EmpMapper;
import com.chuangzhou.pojo.Dept;
import com.chuangzhou.pojo.Emp;
import com.chuangzhou.serivce.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Autowired
private EmpMapper empMapper;
//删除部门信息
@Transactional
@Override
public void delete(Integer id) {
deptMapper.deleteById(id); // 删除部门
int i = 1/ 0; //遇到异常后,部门被删除,但是部门下的员工无法删除
empMapper.deleteByDeptId(id);
}
}
application.yml打开日志:
logging:
level:
org.springframework.jdbc.support.JdbcTransactionManager: debug
执行删除部门后可以看到事务回滚日志:
事务进阶
@Transactional
@Override
public void delete(Integer id) throws Exception {
deptMapper.deleteById(id); // 删除部门
if(true){
throw new Exception("出错了......");
}
empMapper.deleteByDeptId(id);
}
执行以上代码后会发现事务没有回滚,部门被删除了,但是部门下的员工却没有被删除。
原因:
@Trancaction注解:默认情况下只有出现RunTimeException 才回滚异常。
解决:
rollbackFor属性用于控制出现何种异常类型,回滚事务
@Transactional(rollbackFor = {Exception.class}) //所有的异常都会回滚
@Override
public void delete(Integer id) throws Exception {
deptMapper.deleteById(id); // 删除部门
if(true){
throw new Exception("出错了......");
}
empMapper.deleteByDeptId(id);
}
成功回滚: