@Transactional 默认回滚 RuntimeException 若回滚 Exception 需指定
不加@Transactional 不会回滚 IOExcepition
加@Transactional 不会回滚 IOExcepition
指定 rollbackFor= Exception.class 回滚 IOException
嵌套事务 里面的事务不生效 外面生效
public class BusinessException extends Exception {
public BusinessException(String msg) {
super(msg);
}
}
各种情况的测试:
@Autowired
private UserRepository userRepository;
// 不回滚
@Transactional
public void test1() throws Exception {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new Exception("test1 error");
}
// 不回滚
@Transactional
public void test11() throws Exception {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new BusinessException("test11 error");
}
// 回滚
@Transactional(rollbackFor = Exception.class)
public void test2() throws Exception {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new Exception("test2 error");
}
// 回滚
@Transactional(rollbackFor = Exception.class)
public void test21() throws Exception {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new BusinessException("test21 error");
}
// 回滚
@Transactional
public void test3() {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new RuntimeException("test3 runtime error");
}
// 不回滚
@Transactional
public void test4() throws Exception {
User user = new User(1, "15000000000", "d243ewa", "Comma");
test41(user);
throw new Exception("test4 error");
}
// 回滚
@Transactional(rollbackFor = Exception.class)
public void test41(User user) {
saveUser(user);
throw new IOException();
}
// 不回滚
public void test5() throws BusinessException {
test6();
}
// 回滚
@Transactional(rollbackFor = Exception.class)
public void test6() throws BusinessException {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new BusinessException("test6 error");
}
// 回滚
@Transactional(rollbackFor = Exception.class)
public void test7() throws BusinessException {
test8();
}
public void test8() throws BusinessException {
User user = new User(1, "15000000000", "d243ewa", "Comma");
saveUser(user);
throw new BusinessException("test8 error");
}
public User saveUser(User user) {
return userRepository.save(user);
}