springBoot事务的基本使用

单机系统基本注解事务(@Transactional)的使用:
情况1:运行时异常,触发回滚。
@Transactional
public String addUser() throws FileNotFoundException{
userInfoService.addUser(user);
System.out.println(1/0);
}
情况2:非运行时异常,因为rollbackFor默认是:runtimeException, 不触发回滚
@Transactional
public String addUser() throws FileNotFoundException{
userInfoService.addUser(user);
File fl=new File("/dddd");
}
情况3:非运行时异常,指定rollbackFor,发生回滚
@Transactional(rollbackFor = Exception.class)
public String addUser() throws FileNotFoundException{
userInfoService.addUser(user);
File fl=new File("/dddd");
}
情况4:不指定rollbackFor,但使用编程在发生异常时回滚,一般用于切面编程
@Transactional
public String addUser() {
userInfoService.addUser(user);
File fl=new File("/dddd");
try {
FileInputStream fs=new FileInputStream(fl);
} catch (FileNotFoundException e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}

posted @ 2022-07-31 16:37  Logan_626  阅读(155)  评论(0编辑  收藏  举报