Spring管理事务时候,Try catch 处理异常有两种方法
前提:数据库为InnoDB引擎
方法1:手动回滚
在catch语句里面 使用: TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
@Transactional
public void saveRecordSet(TEntity entity){ try { getDao().save(entity); int a = 1 /0; TransactionAspectSupport.currentTransactionStatus().createSavepoint(); } catch (Exception e) { e.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } }
方法2:抛出继续由Spring处理回滚
使用: throw new RuntimeException();抛出异常 最终由Spring检查出异常做出回滚
@Transactional
public void saveRecordSet(TEntity entity){ try { getDao().save(entity); int a = 1 /0; TransactionAspectSupport.currentTransactionStatus().createSavepoint(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } }