Transactional注解的rollbackFor属性,此属性是指定程序中自定义检查异常的回滚情况,如果rollbackFor属性未指定自定义检查异常当发生自定义检查异常时事物是不会回滚的,只有指定了的自定义检查异常事务才会回滚
测试案例
持久层使用的是JPA,save()是JPA原生方法,没有实现,测试案例从service层开始
Service
@Service
public class UserService {
@Autowired
private UserRepo userDao;
@Transactional(rollbackFor = CommonException.class)
public void add(UserEntity entity) throws CommonException {
userDao.save(entity);
throw new CommonException("事物回滚测试");
}
@Transactional
public void save(UserEntity entity) throws CommonException {
userDao.save(entity);
throw new CommonException("事物回滚测试");
}
}
Controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/add")
public void add() {
UserEntity entity = new UserEntity();
try {
entity.setUserAge(19);
entity.setUsername("test-name-yes");
entity.setPassword("test-password-yes");
entity.setUserSex(SexType.BOY);
entity.setPhone("test-phone-yes");
userService.add(entity);
} catch (CommonException e) {
System.out.println("rollbackFor携带自定义异常");
}
}
@PostMapping("/save")
public void save() {
UserEntity entity = new UserEntity();
entity.setUserAge(26);
entity.setUsername("test-name-no");
entity.setPassword("test-password-no");
entity.setUserSex(SexType.BOY);
entity.setPhone("test-phone-no");
try {
userService.save(entity);
} catch (CommonException e) {
System.out.println("rollbackFo不携带自定义异常");
}
}
}
调用两个接口查看数据库中内容为:add接口未成功插入数据到数据库,save接口成功插入数据到数据库
注意rollbackFor属性就算未指定运行时异常,当发生运行时异常时事务也会回滚