SpringBoot开启事务很简单,只需要一个@Transactional注解即可。因为在SpringBoot中已经默认对jpa,jdbc,mybatis开启了事务,引入它们依赖的时候,事务就默认开启了。
下面我们以SpringBoot-整合JPA的案列来实际检验下事务性。
修改StudentServiceImpl中的save实现,我们在成功保存之后跑出一个异常,然后去数据库看是是否有正确保存:
@Override
@Transactional
public Integer save(Student entity) throws Exception {
if (entity.getId() != null) {
Student perz = studentDao.saveAndFlush(entity);
return perz.getId();
}
Student perz = studentDao.save(entity);
int result = 5 / 0;
return perz.getId();
}
然后启动springboot入口类,调用save接口:
这个时候肯定是会跑出异常的,因为0不可以做为除数。那我们现在去数据库看看有没有这条数据。