同时使用@Transactional和try-catch,发现执行以下代码事务会失效,数据还是进行了修改操作
1 @Override 2 @Transactional(rollbackFor = Exception.class) 3 public Boolean updateEngineerBuildInfoByEngineerId(Integer engineerId, Integer departmentId, Integer operatorId,Integer oldOperatorId,Integer engineerType,Integer personId,String personName) { 4 try { 5 //更新工程施工人员信息 6 Engineer engineer = new Engineer(); 7 engineer.setEngineerId(engineerId); 8 engineer.setDepartmentId(departmentId); 9 engineer.setOperatorId(operatorId); 10 baseMapper.updateEngineerBuildInfoByEngineerId(engineer); 11 int a = 2/0; 12 } catch (Exception e) { 13 log.error("转派失败:{}",e.getMessage()); 14 return false; 15 } 16 return true; 17 }
解决方法
方法一:在catch代码块将异常抛出
1 @Override 2 @Transactional(rollbackFor = Exception.class) 3 public Boolean updateEngineerBuildInfoByEngineerId(Integer engineerId, Integer departmentId, Integer operatorId,Integer oldOperatorId,Integer engineerType,Integer personId,String personName) { 4 try { 5 //更新工程施工人员信息 6 Engineer engineer = new Engineer(); 7 engineer.setEngineerId(engineerId); 8 engineer.setDepartmentId(departmentId); 9 engineer.setOperatorId(operatorId); 10 baseMapper.updateEngineerBuildInfoByEngineerId(engineer); 11 int a = 2/0; 12 } catch (Exception e) { 13 log.error("转派失败:{}",e.getMessage()); 14 throw new ServerException(e.getMessage(), e); 15 } 16 return true; 17 }
方法二:在catch代码块中手动事务回滚
1 @Override 2 @Transactional(rollbackFor = Exception.class) 3 public Boolean updateEngineerBuildInfoByEngineerId(Integer engineerId, Integer departmentId, Integer operatorId,Integer oldOperatorId,Integer engineerType,Integer personId,String personName) { 4 try { 5 //更新工程施工人员信息 6 Engineer engineer = new Engineer(); 7 engineer.setEngineerId(engineerId); 8 engineer.setDepartmentId(departmentId); 9 engineer.setOperatorId(operatorId); 10 baseMapper.updateEngineerBuildInfoByEngineerId(engineer); 11 int a = 2/0; 12 } catch (Exception e) { 13 log.error("转派失败:{}",e.getMessage()); 14 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 15 return false; 16 } 17 return true; 18 }
标签:回滚,Transactional,Exception,try,catch,Integer,engineerId,engineer From: https://www.cnblogs.com/yzhmj/p/16847691.html