Spring -- 事务失效
1. 抛出检查异常导致事务不能正确回滚
@Service public class Service1 { @Autowired private AccountMapper accountMapper; @Transactional public void transfer(int from, int to, int amount) throws FileNotFoundException { int fromBalance = accountMapper.findBalanceBy(from); if (fromBalance - amount >= 0) { accountMapper.update(from, -1 * amount); new FileInputStream("aaa"); accountMapper.update(to, amount); } } }
- 
- 
解法:配置 rollbackFor 属性 
- 
2. 业务方法内自己 try-catch 异常导致事务不能正确回滚
@Service public class Service2 { @Autowired private AccountMapper accountMapper; @Transactional(rollbackFor = Exception.class) public void transfer(int from, int to, int amount) { try { int fromBalance = accountMapper.findBalanceBy(from); if (fromBalance - amount >= 0) { accountMapper.update(from, -1 * amount); new FileInputStream("aaa"); accountMapper.update(to, amount); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
- 
- 
解法1:异常原样抛出 - 
在 catch 块添加 throw new RuntimeException(e);
 
- 
- 
解法2:手动设置 TransactionStatus.setRollbackOnly() 
- 
在 catch 块添加 
3. 非 public 方法导致的事务失效
@Service public class Service4 { @Autowired private AccountMapper accountMapper; @Transactional void transfer(int from, int to, int amount) throws FileNotFoundException { int fromBalance = accountMapper.findBalanceBy(from); if (fromBalance - amount >= 0) { accountMapper.update(from, -1 * amount); accountMapper.update(to, amount); } } }
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号