springboot默认开启了事务,如果需要使用事务,直接在service层中的方法体上使用@Transactional注解就可以了
package com.anlysqx.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.anlysqx.dao.UserMapper;
import com.anlysqx.entity.User;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public String addUser(){
String msg = "插入成功";
try{
User user = new User();
user.setUname("木土");
user.setAge(23);
user.setPassword("1111111");
userMapper.insertOneUser(user);
// int i = 1/0;
}catch(Exception e){
msg = "插入失败";
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return msg;
}
}
如代码所示,如果注释掉 int i = 1/0;就会抛出异常,然后自己捕捉到后,手动用事务回滚,不再把异常往外扩散,数据库会插入失败。取消注释后,数据库插入成功。
如果不加@Transactional注解,则数据库会插入成功后报异常,不符合事务的特性。
因此可以看到事务机制起了作用。
controller.java
package com.anlysqx.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.anlysqx.service.UserService;
@RestController
public class InserUserController {
@Autowired
private UserService userService;
@RequestMapping("/insertuser")
@ResponseBody
public String insertOneUser(){
return userService.addUser();
}
}