Example #1
0
  private int execute(Prepared p) {
    beginTransaction(p);

    boolean isTopTransaction = false;
    boolean isNestedTransaction = false;
    Session session = p.getSession();

    try {
      if (!p.isLocal() && p.isBatch()) {
        if (session.isAutoCommit()) {
          session.setAutoCommit(false);
          isTopTransaction = true;
        } else {
          isNestedTransaction = true;
          session.addSavepoint(TransactionCommand.INTERNAL_SAVEPOINT);
        }
      }
      int updateCount = 0;
      switch (p.getType()) {
        case CommandInterface.INSERT:
          updateCount = nestedRouter.executeInsert((Insert) p);
          break;
        case CommandInterface.UPDATE:
          updateCount = nestedRouter.executeUpdate((Update) p);
          break;
        case CommandInterface.DELETE:
          updateCount = nestedRouter.executeDelete((Delete) p);
          break;
        case CommandInterface.MERGE:
          updateCount = nestedRouter.executeMerge((Merge) p);
          break;
      }
      if (isTopTransaction) session.commit(false);
      return updateCount;
    } catch (Exception e) {
      if (isTopTransaction) session.rollback();

      // 嵌套事务出错时提前rollback
      if (isNestedTransaction) session.rollbackToSavepoint(TransactionCommand.INTERNAL_SAVEPOINT);

      throw DbException.convert(e);
    } finally {
      if (isTopTransaction) session.setAutoCommit(true);
    }
  }