注解配置:
在Service层的实现类上加上注解
@Transactional(propagation = Propagation.REQUIRED,isolation= Isolation.DEFAULT)
在Springboot的入口类开启事务@EnableTransactionManagement
测试:Service层执行更新操作后主动抛出异常
@Override
public void updateStudent(Student student, MultipartFile pictureFile) throws IOException
{
if(pictureFile!=null) {
PicUtil picUtil = new PicUtil();
picUtil.setPic(pictureFile, student);
}
studentMapper.updateStudent(student);
if (true) {
throw new RuntimeException("抛异常了");
}
}
结果:执行更新操作后抛出异常,数据库没有发生更新,而是回滚到之前的状态。删去@Transactional后执行更新操作,发现抛出异常后,数据库仍然发生了更新。
在studentMapper.updateStudent(student);处打断点发现,在进行事务管理时,执行了这条语句后数据库并没有更新,而是成功执行完整个方法之后数据库才发生更新,如果这个期间抛出异常,那么数据库将会回滚到之前的状态。