1、问题描述
springboot项目中配置事务,以前通过标签用过,上个内部项目,因为是在别人代码中使用了,发现好像没起作用(然后因为有框架保证,就没计较了),新启动项目又用到,验证了下,springboot项目下配置两个标签就可以了。
2、解决方案
2.1 说明
(1)其实就两个标签,一个用到启动类中(@EnableTransactionManagement),另一个就是那里需要就配置到哪里(@Transactional);
(2)方案,就随便找了个以前的测试项目,一个方法中包含:保存一条数据到数据库中和一个1除以0代码,然后看下加不加事务标签有什么区别;
2.2 代码说明
(1)controller类
@ResponseBody
@GetMapping("/tstest")
public String tstest() {
this.userService.tstest();
return "SUCCESS";
}
(2)service类
public void tstest() {
//保存
UserEntity userEntity = new UserEntity();
userEntity.setType(0);
userEntity.setOpenid("1111");
insert(userEntity);
//报错,回滚
int i = 1/0;
System.out.println(i);
}
2.3 验证1,没有事务
不加事务标签,代码如上。
(1)先清空数据库;
(2)执行tstest请求;

发现insert代码行执行完,数据就存到数据库中了。

接着执行完成(1/0),虽然报错代码报错,但是数据库中数据还是存在的,数据没有回滚,没有保持一致性。

2.4 验证2,有事务
(1)增加两个标签,一个是启动类方法上,一个是tstest方法上。 

(2)首先清除数据,执行到insert处 
发现虽然insert代码行执行完成了,但是这时候数据库中并没有数据,然后执行完,代码报错,数据回滚,数据库中并没有存入数据,说明事务起到到该有的作用,数据回滚了。

更多信息请关注公众号:「软件老王」,关注不迷路,软件老王和他的IT朋友们,分享一些他们的技术见解和生活故事。 
|