Mybatis底層原理學習(二):從原始碼角度分析一次查詢操作過程

深夜程猿發表於2018-03-02

在閱讀這篇文章之前,建議先閱讀一下我之前寫的兩篇文章,對理解這篇文章很有幫助,特別是Mybatis新手:

寫給mybatis小白的入門指南

mybatis底層原理學習(一):SqlSessionFactory和SqlSession的建立過程

如果你想獲得更好的閱讀體驗,可以點選這裡:Mybatis底層原理學習(二):從原始碼角度分析一次查詢操作過程

(1)在使用Mybatis運算元據庫的時候,每一次的CRUD操作都會去獲取一次對映配置檔案(mapper xml檔案)對應的sql對映。每一個sql對映在記憶體快取中(建立SqlSessionFactory之前就快取在記憶體中了)都會有唯一ID,就是sql對映所在xml檔案的名稱空間加上sql對映配置節點的id值。
(2)Mapper xml檔案的名稱空間使用的是類的全路徑名,這樣做的好處是可以全域性唯一,又可以通過反射獲取對應的Mapper類。可以理解成每一個mapper xml檔案對應一個Mapper類。
(3)mapper xml檔案每一個sql對映節點的id屬性值對應類的一個方法。我們在配置sql對映的時候也必須這樣做,因為Mybatis的底層就是使用反射機制來獲取執行方法的全路徑作為ID來獲取sql的對映配置的。
(4)每一個和mapper xml檔案關聯的類,都是Mapper類,在執行過程,通過動態代理,執行對應的方法。Mybatis是如何判斷哪些類是Mapper類的呢?其實只有在執行時才會知道。在載入Mybatis配置檔案中,通過解析mapper xml檔案快取了所有的sql對映配置,在呼叫SqlSession的getMapper方法獲取Mapper類的時候才會生成代理類。

現在,我們來從原始碼角度分析Mapper代理類的建立過程,demo原始碼在後面給出 demo示例:

public class Main {

    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);
        Article article = mapper.selectOne(1);
        LOGGER.info("title:" + article.getTitle() + " " + "content:" + article.getContent());
    }

}

複製程式碼

我們在這行程式碼處搭上斷點:

ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);
複製程式碼

Debug進去,執行下面程式碼:

public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
複製程式碼

configuration持有Mybatis的基本配置資訊,繼續看看getMapper方法的執行:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
複製程式碼

mapperRegistry快取了所有的SQL對映配置資訊,在載入解析Mybatis配置檔案(例子是mybatis)和mapper xml檔案的時候完成快取的,繼續看getMapper的執行:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 這裡首先會獲取Mapper代理類工廠,拿到代理工廠就建立代理類
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 建立Mapper代理類
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
複製程式碼

通過動態代理機制建立Mapper代理類

protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
複製程式碼

到這裡,動態代理類建立完成。 通過分析了原始碼執行過程,Mapper代理類的建立過程弄清楚了,大體就是通過從快取中獲取sql對映配置的id(類全路徑名+方法名)來通過動態代理機制建立代理類,實際執行的CRUD是執行動態代理類的方法。 執行CRUD操作的時候,我們都會執行到動態代理類的invoke方法:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }
複製程式碼

最後找到對映的方法,執行mapperMethod.execute(sqlSession, args)。 通過程式碼我們可以看到,會根據執行方法的操作型別(CRUD)執行不同的邏輯處理。

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    switch (command.getType()) {
      case INSERT: {
    	Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT:
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName() 
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }
複製程式碼

我們分析一下查詢select:

if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) {
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
        }
複製程式碼

首先根據方法返回型別的不同執行不同的邏輯,最終會呼叫SqlSession的selectXXX方法,

public <T> T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    List<T> list = this.<T>selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }
複製程式碼

List<T> list = this.<T>selectList(statement, parameter);這行程式碼邏輯處理:

public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }
複製程式碼

繼續進去:

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
複製程式碼

到這一步,是呼叫執行器Executor的query方法:

 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

複製程式碼

進去query方法:

 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, parameterObject, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
複製程式碼

繼續進去query方法:

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());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }
複製程式碼

真正訪問資料庫的是這行程式碼:list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);

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 {
      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;
  }
複製程式碼

查詢操作由doQuery方法處理,這段程式碼就接近原生JDBC操作了,首先會獲取語句處理器,然後開始執行語句,執行完,還會對結果進行結果集處理,返回處理的結果集,這裡就不多分析了

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }
複製程式碼

我們在使用Mybatis進行CRUD操作的時候,大體過程是這樣:

  • 解析基本配置檔案和Sql對映配置檔案(mapper xml)檔案,快取配置檔案節點內容在記憶體(一般此步驟只會執行一次,多次呼叫都會複用快取結果)
  • 獲取SqlSession,通過SqlSession來獲取Mapper類,生成Mapper類的代理
  • 執行CRUED操作

當然,這個過程Mybatis還做了很多事情,Sql的解析,結果集的處理……等操作我們在這篇文章不分析,後面會有文章分析。這篇文章目的是分析Mapper代理類的建立過程和簡單分析一個查詢操作的過程。

原始碼地址

學習更多原始碼分析文章,歡迎關注微信公眾號:深夜程猿
【福利】關注公眾號回覆關鍵字,還可獲得視訊學習資源,求職簡歷模板

Mybatis底層原理學習(二):從原始碼角度分析一次查詢操作過程

相關文章