mybatis源碼解析七之對性能的優化

session 一級緩存優化

/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor;

import static org.apache.ibatis.executor.ExecutionPlaceholder.EXECUTION_PLACEHOLDER;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.statement.StatementUtil;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.logging.jdbc.ConnectionLogger;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.type.TypeHandlerRegistry;

/**
 * @author Clinton Begin
 */
public abstract class BaseExecutor implements Executor {

  private static final Log log = LogFactory.getLog(BaseExecutor.class);
 // Transaction 對象,實現事務的提交、回滾和關閉操作
  protected Transaction transaction;
 // 其中封裝的Executor 對象
  protected Executor wrapper;
 // 延遲加載隊列
  protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
  // 一級緩存,用於緩存該Executor 對象查詢結果集映射得到的結果對象
  protected PerpetualCache localCache;
 // 一級緩存,用於緩存輸出類型的參數
  protected PerpetualCache localOutputParameterCache;
  protected Configuration configuration;

  //用來記錄嵌套查詢的層數
  protected int queryStack;
  private boolean closed;

  protected BaseExecutor(Configuration configuration, Transaction transaction) {
    this.transaction = transaction;
    this.deferredLoads = new ConcurrentLinkedQueue<>();
    this.localCache = new PerpetualCache("LocalCache");
    this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
    this.closed = false;
    this.configuration = configuration;
    this.wrapper = this;
  }

  @Override
  public Transaction getTransaction() {
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    return transaction;
  }

  @Override
  public void close(boolean forceRollback) {
    try {
      try {
        rollback(forceRollback);
      } finally {
        if (transaction != null) {
          transaction.close();
        }
      }
    } catch (SQLException e) {
      // Ignore. There's nothing that can be done at this point.
      log.warn("Unexpected exception on closing transaction.  Cause: " + e);
    } finally {
      transaction = null;
      deferredLoads = null;
      localCache = null;
      localOutputParameterCache = null;
      closed = true;
    }
  }

  @Override
  public boolean isClosed() {
    return closed;
  }

  @Override
  public int update(MappedStatement ms, Object parameter) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
   //判斷當前Executor 是否已經關閉
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    //clearLocalCache ()方法中會調用localCache 、localOutputParameterCache 兩個
//緩存的clear ()方法完成清理工作。這是影響一級緩存中數據存活時長的第三個方面
    clearLocalCache();
    return doUpdate(ms, parameter);
  }

  @Override
  public List<BatchResult> flushStatements() throws SQLException {
    return flushStatements(false);
  }

  public List<BatchResult> flushStatements(boolean isRollBack) throws SQLException {
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    //參數isRollBack表示是否執行Executor 中緩存的SQL 語句,false 表示執行,true 表示不執行
    return doFlushStatements(isRollBack);
  }

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    //獲取BoundSql 對象
    BoundSql boundSql = ms.getBoundSql(parameter);
   // 創建CacheKey 對象
    CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
   // 調用query ()的另一個重載,繼續後續處理
    return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
  }

  @SuppressWarnings("unchecked")
  @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
  //檢測當前Executor 是否已經關閉
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      //非嵌套查詢,並且< select >節點配置的flushCache 屬性爲true 時,纔會清空一級緩存
     // flushCache 配置項是影響一級緩存中結果對象存活時長的第一個方面
      clearLocalCache();
    }
    List<E> list;
    try {
      //培加查詢層數
      queryStack++;
      //查詢一級緩存
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        //針對存儲過程調用的處理, 其功能是: 在一級緩存命中時,獲取緩存中保存的輸出類型參數,並設置到用戶傳入的實參( parameter )對象中
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        //其中會調用doQuery ()方法完成數據庫查詢,並得到映射後的結果對象
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      //當前查詢完成,查詢層數減少
      queryStack--;
    }
    if (queryStack == 0) {
      //延遲加載
     // 在最外層的查詢結束時,所有嵌套查詢也已經完成,相關緩存項也已經完全加載,所以在這裏可以
      //觸發DeferredLoad 加載一級緩存中記錄的嵌套查詢的結果對象
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
    //加裁完成後, 清空deferredLoads 集合
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
       //根據localCacheScope 配置決定是否清空一級緩存,localCacheScope 配置是影響一級緩
       //存中結果對象存活時長的第二個方面
        clearLocalCache();
      }
    }
    return list;
  }

  @Override
  public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameter);
    return doQueryCursor(ms, parameter, rowBounds, boundSql);
  }

  @Override
  public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType) {
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
   // 創建DeferredLoad 對象
    DeferredLoad deferredLoad = new DeferredLoad(resultObject, property, key, localCache, configuration, targetType);
    if (deferredLoad.canLoad()) {
     //一級緩存中已經記錄了指定查詢的結果對象, 直接從緩存中加載對象,並設置到外層對象中
      deferredLoad.load();
    } else {
     //將DeferredLoad 對象添加到deferredLoads 隊列中,待整個外層查詢結束後,再加載該結果對象
      deferredLoads.add(new DeferredLoad(resultObject, property, key, localCache, configuration, targetType));
    }
  }

  @Override
  public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
    //檢測當前Executor 是否已經關閉
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    //創建CacheKey 對象
    CacheKey cacheKey = new CacheKey();
    //將MappedStatement 的id 添加到Cache Key 對象中
    cacheKey.update(ms.getId());
    //將off set 添加到CacheKey 對象中
    cacheKey.update(rowBounds.getOffset());
   //將limit 添加到CacheKey 對象中
    cacheKey.update(rowBounds.getLimit());
    //將SQL 語句添加到CacheKey 對象中
    cacheKey.update(boundSql.getSql());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
    // mimic DefaultParameterHandler logic
    //獲取用戶傳入的實參,並添加.f1J CacheKey 對象中
    for (ParameterMapping parameterMapping : parameterMappings) {
      //過濾輸出類型的參數
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        Object value;
        String propertyName = parameterMapping.getProperty();
        if (boundSql.hasAdditionalParameter(propertyName)) {
          value = boundSql.getAdditionalParameter(propertyName);
        } else if (parameterObject == null) {
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          value = parameterObject;
        } else {
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        //將實參添加到CacheKey 對象中
        cacheKey.update(value);
      }
    }
    //如果Environment 的id 不爲空,則將其添加到CacheKey 中
    if (configuration.getEnvironment() != null) {
      // issue #176
      cacheKey.update(configuration.getEnvironment().getId());
    }
    return cacheKey;
  }

  @Override
  public boolean isCached(MappedStatement ms, CacheKey key) {
   //檢測緩存中是否緩存了CacheKey 對應的對象
    return localCache.getObject(key) != null;
  }

  @Override
  public void commit(boolean required) throws SQLException {
    if (closed) {
      throw new ExecutorException("Cannot commit, transaction is already closed");
    }
   //清空一級緩存
    clearLocalCache();
    //執行緩存的SQL 語句,其中調用了flushStatements(false )方法
    flushStatements();
   //根據required 參數決定是否提交事務
    if (required) {
      transaction.commit();
    }
  }

  @Override
  public void rollback(boolean required) throws SQLException {
    if (!closed) {
      try {
        clearLocalCache();
        flushStatements(true);
      } finally {
        if (required) {
          transaction.rollback();
        }
      }
    }
  }

  @Override
  public void clearLocalCache() {
    if (!closed) {
      localCache.clear();
      localOutputParameterCache.clear();
    }
  }

  protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException;

  protected abstract List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException;

  protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
      throws SQLException;

  protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql)
      throws SQLException;

  protected void closeStatement(Statement statement) {
    if (statement != null) {
      try {
        statement.close();
      } catch (SQLException e) {
        // ignore
      }
    }
  }

  /**
   * Apply a transaction timeout.
   *
   * @param statement
   *          a current statement
   * @throws SQLException
   *           if a database access error occurs, this method is called on a closed <code>Statement</code>
   * @since 3.4.0
   * @see StatementUtil#applyTransactionTimeout(Statement, Integer, Integer)
   */
  protected void applyTransactionTimeout(Statement statement) throws SQLException {
    StatementUtil.applyTransactionTimeout(statement, statement.getQueryTimeout(), transaction.getTimeout());
  }

  private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
    if (ms.getStatementType() == StatementType.CALLABLE) {
      final Object cachedParameter = localOutputParameterCache.getObject(key);
      if (cachedParameter != null && parameter != null) {
        final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
        final MetaObject metaParameter = configuration.newMetaObject(parameter);
        for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
          if (parameterMapping.getMode() != ParameterMode.IN) {
            final String parameterName = parameterMapping.getProperty();
            final Object cachedValue = metaCachedParameter.getValue(parameterName);
            metaParameter.setValue(parameterName, cachedValue);
          }
        }
      }
    }
  }

  private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    // 在緩存中添加佔位符
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      //調用doQuery ()方法(抽象方法),完成數據庫查詢操作,並返回結果對象
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
      //刪除佔位符
      localCache.removeObject(key);
    }
    //將真正的結果對象添加到一級緩存中
    localCache.putObject(key, list);
    //是否爲存儲過程調用
    if (ms.getStatementType() == StatementType.CALLABLE) {
     //緩存輸出類型的參數
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

  protected Connection getConnection(Log statementLog) throws SQLException {
    Connection connection = transaction.getConnection();
    if (statementLog.isDebugEnabled()) {
      return ConnectionLogger.newInstance(connection, statementLog, queryStack);
    } else {
      return connection;
    }
  }

  @Override
  public void setExecutorWrapper(Executor wrapper) {
    this.wrapper = wrapper;
  }

  private static class DeferredLoad {
    //外層對象對應的MetaObject 對象
    private final MetaObject resultObject;
    //延遲加載的屬性名稱
    private final String property;
    //延遲加載的屬性的類型
    private final Class<?> targetType;
    //延遲加載的結果對象在一級緩存中相應的CacheKey 對象
    private final CacheKey key;
    //一級緩存,與BaseExecutor.localCache 字段指向同- PerpetualCache 對象
    private final PerpetualCache localCache;
    private final ObjectFactory objectFactory;
    //ResultExtractor 負責結果對象的類型轉換
    private final ResultExtractor resultExtractor;

    // issue #781
    public DeferredLoad(MetaObject resultObject,
                        String property,
                        CacheKey key,
                        PerpetualCache localCache,
                        Configuration configuration,
                        Class<?> targetType) {
      this.resultObject = resultObject;
      this.property = property;
      this.key = key;
      this.localCache = localCache;
      this.objectFactory = configuration.getObjectFactory();
      this.resultExtractor = new ResultExtractor(configuration, objectFactory);
      this.targetType = targetType;
    }

    public boolean canLoad() {
      return
       //檢測緩存是否存在指定的結采對象
        localCache.getObject(key) != null
      //檢測是否爲佔位符
        && localCache.getObject(key) != EXECUTION_PLACEHOLDER;
    }

    public void load() {
      @SuppressWarnings("unchecked")
      // we suppose we get back a List
       //從緩存中查詢指定的結采對象
      List<Object> list = (List<Object>) localCache.getObject(key);
      //將緩存的結果對象轉換成指定類型
      Object value = resultExtractor.extractObjectFromList(list, targetType);
     // 設直到外層對象的對應屬性
      resultObject.setValue(property, value);
    }

  }

}

二級緩存優化

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 * 爲指定的命名空間創建相應的Cache 對象作爲
 * 其二級緩存,默認是PerpetualCache 對象
 */
public class CachingExecutor implements Executor {
@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
      //步驟1 :獲取BoundSql 對象,
    BoundSql boundSql = ms.getBoundSql(parameterObject);
      //創建CacheKey 對象
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
//獲取查詢語句所在命名空間對應的二級緩存
    Cache cache = ms.getCache();
//步驟2 :是否開啓了二級緩存功能
    if (cache != null) {
     // 根據< select >節點的配置,決定是否需妥清空二級緩存
      flushCacheIfRequired(ms);
     //檢測SQL 節點的useCache 配置以及是否使用了resultHandler 配置
      if (ms.isUseCache() && resultHandler == null) {
       //步驟3 :二級緩存不能保存輸出類型的參數, 如果查詢操作調用了包含輸出參數的存儲過程,則報錯
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
         //步驟4 :查詢二級緩存
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
         //步驟5 :二級緩存沒有相應的結采對象,調用封裝的Executor 對象的query ()方法,其中會允查詢一級緩存
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
         //將查詢結果保存到TransactionalCache.entriesToAddOnCornrnit 集合中
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
   //沒有啓動二級緩存,直接調用底層Exe cutor 執行數據庫查詢操作
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }


  @Override
  public void commit(boolean required) throws SQLException {
   // 調用底層的Executor 提交事務
    delegate.commit(required);
    //邊歷所有相關的TransactionalCache 對象執行commit ()方法
    tcm.commit();
  }

  @Override
  public void rollback(boolean required) throws SQLException {
    try {
     //調用底層的Executor 回滾事務
      delegate.rollback(required);
    } finally {
      if (required) {
        //遍歷所有相關的TransactionalCache 對象執行rollback ()方法
        tcm.rollback();
      }
    }
  }
  }

Statement重用優化

/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;

/**
 * @author Clinton Begin
 * 嘗試重用StaternentMap 中緩存的Statement 對象。
 */
public class ReuseExecutor extends BaseExecutor {

  private final Map<String, Statement> statementMap = new HashMap<>();

  public ReuseExecutor(Configuration configuration, Transaction transaction) {
    super(configuration, transaction);
  }

  @Override
  public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
    Statement stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.update(stmt);
  }

  @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    Statement stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.query(stmt, resultHandler);
  }

  @Override
  protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
    Statement stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.queryCursor(stmt);
  }

  @Override
  public List<BatchResult> doFlushStatements(boolean isRollback) {
    for (Statement stmt : statementMap.values()) {
    //遍歷staternentMap 集合並關閉其中的Statement 對象
      closeStatement(stmt);
    }
   //清空staternentMap 緩存
    statementMap.clear();
   //返回空集合
    return Collections.emptyList();
  }

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    BoundSql boundSql = handler.getBoundSql();
   //獲取SQL 語句
    String sql = boundSql.getSql();
  //檢測是否緩存了相同模式的SQL 語句所對應的Statement 對象
    if (hasStatementFor(sql)) {
     //獲取statementMap 集合中緩存的Statement 對象
      stmt = getStatement(sql);
     //修改超時時間
      applyTransactionTimeout(stmt);
    } else {
    //獲取數據庫連接
      Connection connection = getConnection(statementLog);
    //創建新的Statement 對象,並緩存到staternentMap 集合中
      stmt = handler.prepare(connection, transaction.getTimeout());
      putStatement(sql, stmt);
    }
   //處理佔位符
    handler.parameterize(stmt);
    return stmt;
  }

  private boolean hasStatementFor(String sql) {
    try {
      Statement statement = statementMap.get(sql);
      return statement != null && !statement.getConnection().isClosed();
    } catch (SQLException e) {
      return false;
    }
  }

  private Statement getStatement(String s) {
    return statementMap.get(s);
  }

  private void putStatement(String sql, Statement stmt) {
    statementMap.put(sql, stmt);
  }

}

批量處理SQL優化

/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;

/**
 * @author Jeff Butler
 */
public class BatchExecutor extends BaseExecutor {

  public static final int BATCH_UPDATE_RETURN_VALUE = Integer.MIN_VALUE + 1002;
//緩存多個Statement 對象其中每個Statement 對象中都緩存了多條SQL 語句
  private final List<Statement> statementList = new ArrayList<>();
//記錄批處理的結果
  private final List<BatchResult> batchResultList = new ArrayList<>();
// 記錄當前執行的S QL 語句
  private String currentSql;
//記錄當前執行的MappedStatement 對象
  private MappedStatement currentStatement;

  public BatchExecutor(Configuration configuration, Transaction transaction) {
    super(configuration, transaction);
  }

  @Override
  public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
 //獲取配置對象
    final Configuration configuration = ms.getConfiguration();
  //創建StatementHandler 對象
    final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
    final BoundSql boundSql = handler.getBoundSql();
//獲取SQL 語句
    final String sql = boundSql.getSql();
    final Statement stmt;
//如果當前執行的SQL 模式與上次執行的SQL 模式相同且對應的MappedStatement 對象相同
    if (sql.equals(currentSql) && ms.equals(currentStatement)) {
      //獲取statementList 集合中最後一個Statement 對象
      int last = statementList.size() - 1;
      stmt = statementList.get(last);
      applyTransactionTimeout(stmt);
      //綁定實參, 處理” ? ” 佔位符
      handler.parameterize(stmt);// fix Issues 322
      //查找對應的BatchResult 對象,並記錄用戶傳入的實參
      BatchResult batchResult = batchResultList.get(last);
      batchResult.addParameterObject(parameterObject);
    } else {
      Connection connection = getConnection(ms.getStatementLog());
      //創建新的Statement 對象
      stmt = handler.prepare(connection, transaction.getTimeout());
      //綁定實參,處理” ? ”佔位符
      handler.parameterize(stmt);    // fix Issues 322
      //更新currentSql 和currentStatement
      currentSql = sql;
      currentStatement = ms;
      //將新創建的Statement 對象添加到statementList 集合中
      statementList.add(stmt);
      //添加新的BatchResult 對象
      batchResultList.add(new BatchResult(ms, sql, parameterObject));
    }
    //底層通過調用Statement.addBatch ()方法添加SQL 語句
    handler.batch(stmt);
    return BATCH_UPDATE_RETURN_VALUE;
  }

  @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
      throws SQLException {
    Statement stmt = null;
    try {
      flushStatements();
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameterObject, rowBounds, resultHandler, boundSql);
      Connection connection = getConnection(ms.getStatementLog());
      stmt = handler.prepare(connection, transaction.getTimeout());
      handler.parameterize(stmt);
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

  @Override
  protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
    flushStatements();
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
    Connection connection = getConnection(ms.getStatementLog());
    Statement stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    Cursor<E> cursor = handler.queryCursor(stmt);
    stmt.closeOnCompletion();
    return cursor;
  }

  @Override
  public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
    try {
    // results 集合用於儲存批處理的結果
      List<BatchResult> results = new ArrayList<>();
      //如果明確指定了要回滾事務,則直接返回空集合,忽略statementList 集合中記錄的SQL 語句
      if (isRollback) {
        return Collections.emptyList();
      }
      //遙歷statementList 集合
      for (int i = 0, n = statementList.size(); i < n; i++) {
      // 獲取Statement 對象
        Statement stmt = statementList.get(i);
        applyTransactionTimeout(stmt);
        //獲取對應BatchResult 對象
        BatchResult batchResult = batchResultList.get(i);
        try {
          // 調用Statement.executeBatch ()方法批量執行其中記錄的SQL 語句,並使用返回的int數組
// 更新BatchResult.updateCounts 字段,其中每一個元素都表示一條SQL 語句影響的記錄條數
          batchResult.setUpdateCounts(stmt.executeBatch());
          MappedStatement ms = batchResult.getMappedStatement();
          List<Object> parameterObjects = batchResult.getParameterObjects();
          //獲取配置的KeyGenerator 對象
          KeyGenerator keyGenerator = ms.getKeyGenerator();
          if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
            Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
            //獲取數據庫生成的主鍵,並設置到parameterObjects 中
            jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
          } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141
            //對於其他類型的KeyGenerator ,會調用其processAfter ()方法
            for (Object parameter : parameterObjects) {
              keyGenerator.processAfter(this, ms, stmt, parameter);
            }
          }
          // Close statement to close cursor #1109
          closeStatement(stmt);
        } catch (BatchUpdateException e) {
          StringBuilder message = new StringBuilder();
          message.append(batchResult.getMappedStatement().getId())
              .append(" (batch index #")
              .append(i + 1)
              .append(")")
              .append(" failed.");
          if (i > 0) {
            message.append(" ")
                .append(i)
                .append(" prior sub executor(s) completed successfully, but will be rolled back.");
          }
          throw new BatchExecutorException(message.toString(), e, results, batchResult);
        }
        //添加BatchResult 到results 集合
        results.add(batchResult);
      }
      return results;
    } finally {
      for (Statement stmt : statementList) {
        //關閉所有Statement 對象,並清空current Sql 字段、清空statement List 集合、清空batchResultList 集合
        closeStatement(stmt);
      }
      currentSql = null;
      statementList.clear();
      batchResultList.clear();
    }
  }

}

懶加載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章