Spring Boot整合事务管理
在Spring Boot中推荐使用@Transactional注解来申明事务。
首先需要导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
当引入jdbc依赖之后,Spring Boot会自动默认分别注入DataSourceTransactionManager或JpaTransactionManager,所以我们不需要任何额外配置就可以用@Transactional注解进行事务的使用。
之后在Service中添加@Transactional注解就可以了。
我们利用之前的一篇博文例子来做Spring Boot的事务管理的demo:Spring Boot整合使用mybatis
在我们的UserMapper类中加入:
@Insert("INSERT INTO USERS(ID, USERNAME) VALUES(#{id}, #{name})")
int insert(@Param("id") Integer id, @Param("name") String name);
然后我们来建一个service类
package com.cc.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cc.springboot.mapper.UserMapper;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int addUser(Integer id,String name){
int insertUser = userMapper.insert(id, name);
int i = 1 / 0;
return insertUser;
}
}
然后我们来完善我们的IndexController
package com.cc.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cc.springboot.entity.UserEntity;
import com.cc.springboot.mapper.UserMapper;
import com.cc.springboot.service.UserService;
@Controller
public class IndexController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/getUserName")
public UserEntity getUserName(String name) {
return userMapper.findByName(name);
}
@ResponseBody
@RequestMapping("/inserUser")
public String addUser(Integer id,String name) {
userService.addUser(id, name);
return "success";
}
}
启动的APP类加上扫描service
现在我们来启动访问一下:
http://localhost:8080/inserUser?id=123&name=aaa
结果发现报错了。
查看数据库发现添加了一条记录。
这不是我们想看到的,所以我们现在要给我们的代码加上事务处理。
在service类中加入:
package com.cc.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cc.springboot.mapper.UserMapper;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public int addUser(Integer id,String name){
int insertUser = userMapper.insert(id, name);
int i = 1 / 0;
return insertUser;
}
}
我们现在重新启动访问:
http://localhost:8080/inserUser?id=321&name=ccc
数据库没有加入数据,说明我们的事务管理已经整合好了。