1. 程式人生 > >Spring程式設計式事務的使用

Spring程式設計式事務的使用

  • 引入事務管理器
@Autowired
TransactionTemplate transactionTemplate;

@Autowired
PlatformTransactionManager transactionManager;
  • 使用方式1
//開啟事務儲存資料
boolean result = transactionTemplate.execute(new TransactionCallback<Boolean>() {
    @Override
    public Boolean doInTransaction(TransactionStatus status) {
        try
{ // TODO something } catch (Exception e) { //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手動開啟事務回滾 status.setRollbackOnly(); logger.error(e.getMessage(), e); return false; } return true; } });
  • 使用方式2
/**
 * 定義事務
 */
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setReadOnly(false);
//隔離級別,-1表示使用資料庫預設級別
def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = transactionManager.getTransaction(def
); try { //TODO something transactionManager.commit(status); } catch (Exception e) { transactionManager.rollback(status); throw new InvoiceApplyException("異常失敗"); }
  • 使用方式3
SqlSession sqlSession = null;
try {
    sqlSession = otInvSqlSessionFactory.openSession(ExecutorType.BATCH, true);
    XXXXXMapper xXxxMapper = sqlSession.getMapper(XXXXXMapper.class);
    sqlSession.commit();
}catch(Exception e){
    if (null != otInvSqlSession) {
        sqlSession.rollback(true);
        logger.error("資料回滾", e);
    }
}finally {
    if (null != sqlSession) {
        sqlSession.clearCache();
        sqlSession.close();
    }
}