1.springboot与事务管理
-
因为导入了mybatis-springboot依赖,所以自动导入了spring-tx依赖,导入的是DataSourceTransactionManager
-
jpa导入的是JpaTransactionManager
1.不加事务管理时,不管是运行异常还是受查异常数据都会插入
@Service
public class StudentServiceImp implements StudentService {
@Resource
private IStudentDao studentDao;
@Override
public void addStudent(Student student) throws Exception {
studentDao.addStudent(student);
//这里发生运行异常
// int a=9/0;
//这里发生的是受查异常
if (true){
throw new Exception("受查异常");
}
studentDao.addStudent(student);
}
}
2.添加了事务管理后,运行异常不会插入,受查异常还是会插入(加入@Transactional)
@Service
@Transactional
public class StudentServiceImp implements StudentService {
@Resource
private IStudentDao studentDao;
@Override
public void addStudent(Student student) throws Exception {
studentDao.addStudent(student);
//这里发生运行异常
// int a=9/0;
//这里发生的是受查异常
if (true){
throw new Exception("受查异常");
}
studentDao.addStudent(student);
}
}
3.发生受查异常错误时,为了不让数据插入,在serviceImp中加入@Transactional(rollbackFor = Exction.class)(这个Exception范围有点大)
@Service
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImp implements StudentService {
@Resource
private IStudentDao studentDao;
@Override
public void addStudent(Student student) throws Exception {
studentDao.addStudent(student);
//这里发生运行异常
// int a=9/0;
//这里发生的是受查异常
if (true){
throw new Exception("受查异常");
}
studentDao.addStudent(student);
}
}