Spring-Boot捕获处理异常并让事务回滚
1.不捕获异常可以正常回滚
@Transactional(rollbackFor = Exception.class) @Override public boolean testTransaction() { baseMapper.updateById(new Person().setId(1).setTicket(10)); Integer i = null; i = i.intValue() + 1; return false; }
缺点:如果上层(control)没有捕获异常,进程就会停止
2.捕获异常,并回滚
@Transactional(rollbackFor = Exception.class) @Override public boolean testTransaction() { baseMapper.updateById(new Person().setId(1).setTicket(10)); try { Integer i = null; i = i.intValue() + 1; } catch (Exception e) { log.info("error: {}", e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } return false; }
核心就是下面这句代码(手动回滚事务)
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();