Mybatis原始碼解析之執行SQL語句

京東雲開發者發表於2022-12-13

作者:鄭志傑

mybatis 運算元據庫的過程

// 第一步:讀取mybatis-config.xml配置檔案
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 第二步:構建SqlSessionFactory(框架初始化)
SqlSessionFactory sqlSessionFactory = new  SqlSessionFactoryBuilder().bulid();
// 第三步:開啟sqlSession
SqlSession session = sqlSessionFactory.openSession();
// 第四步:獲取Mapper介面物件(底層是動態代理)
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
// 第五步:呼叫Mapper介面物件的方法運算元據庫;
Account account = accountMapper.selectByPrimaryKey(1);

 

透過呼叫 session.getMapper (AccountMapper.class) 所得到的 AccountMapper 是一個動態代理物件,所以執行
accountMapper.selectByPrimaryKey (1) 方法前,都會被 invoke () 攔截,先執行 invoke () 中的邏輯。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //  要執行的方法所在的類如果是Object,直接呼叫,不做攔截處理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
            //如果是預設方法,也就是java8中的default方法
        } else if (isDefaultMethod(method)) {
            // 直接執行default方法
            return invokeDefaultMethod(proxy, method, args);
        }
    } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
    } 
    // 從快取中獲取MapperMethod
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
}

 

從 methodCache 獲取對應 DAO 方法的 MapperMethod

MapperMethod 的主要功能是執行 SQL 語句的相關操作,在初始化的時候會例項化兩個物件:SqlCommand(Sql 命令)和 MethodSignature(方法簽名)。

  /**
   * 根據Mapper介面型別、介面方法、核心配置物件 構造MapperMethod物件
   * @param mapperInterface
   * @param method
   * @param config
   */
  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    // 將Mapper介面中的資料庫操作方法(如Account selectById(Integer id);)封裝成方法簽名MethodSignature
    this.method = new MethodSignature(config, mapperInterface, method);
  }

 

new SqlCommand()呼叫 SqlCommand 類構造方法:

 public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      // 獲取Mapper介面中要執行的某個方法的方法名
      // 如accountMapper.selectByPrimaryKey(1)
      final String methodName = method.getName();
      // 獲取方法所在的類
      final Class<?> declaringClass = method.getDeclaringClass();
      // 解析得到Mapper語句物件(對配置檔案中的<mapper></mapper>中的sql語句進行封裝)
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        // 如com.bjpowernode.mapper.AccountMapper.selectByPrimaryKey
        name = ms.getId();
        // SQL型別:增 刪 改 查
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }
  private MapperMethod cachedMapperMethod(Method method) {
     MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
     if (mapperMethod == null) {
         mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
         this.methodCache.put(method, mapperMethod);
     }
     return mapperMethod;
 }

 

呼叫 mapperMethod.execute (sqlSession, args)

在 mapperMethod.execute () 方法中,我們可以看到:mybatis 定義了 5 種 SQL 操作型別:
insert/update/delete/select/flush。其中,select 操作型別又可以分為五類,這五類的返回結果都不同,分別對應:

・返回引數為空:executeWithResultHandler ();

・查詢多條記錄:executeForMany (),返回物件為 JavaBean

・返參物件為 map:executeForMap (), 透過該方法查詢資料庫,最終的返回結果不是 JavaBean,而是 Map

・遊標查詢:executeForCursor ();關於什麼是遊標查詢,自行百度哈;

・查詢單條記錄: sqlSession.selectOne (),透過該查詢方法,最終只會返回一條結果;

透過原始碼追蹤我們可以不難發現:當呼叫 mapperMethod.execute () 執行 SQL 語句的時候,無論是
insert/update/delete/flush,還是 select(包括 5 種不同的 select), 本質上時透過 sqlSession 呼叫的。在 SELECT 操作中,雖然呼叫了 MapperMethod 中的方法,但本質上仍是透過 Sqlsession 下的 select (), selectList (), selectCursor (), selectMap () 等方法實現的。

而 SqlSession 的內部實現,最終是呼叫執行器 Executor(後面會細說)。這裡,我們可以先大概看一下 mybatis 在執行 SQL 語句的時候的呼叫過程:

Mybatis原始碼解析之執行SQL語句

 以accountMapper.selectByPrimaryKey (1) 為例:

・呼叫 SqlSession.getMapper ():得到 xxxMapper (如 UserMapper) 的動態代理物件;

・呼叫
accountMapper.selectByPrimaryKey (1):在 xxxMapper 動態代理內部,會根據要執行的 SQL 語句型別 (insert/update/delete/select/flush) 來呼叫 SqlSession 對應的不同方法,如 sqlSession.insert ();

・在 sqlSession.insert () 方法的實現邏輯中,又會轉交給 executor.query () 進行查詢;

・executor.query () 又最終會轉交給 statement 類進行操作,到這裡就是 jdbc 操作了。

 

有人會好奇,為什麼要透過不斷的轉交,SqlSession->Executor->Statement,而不是直接呼叫 Statement 執行 SQL 語句呢?因為在呼叫 Statement 之前,會處理一些共性的邏輯,如在 Executor 的實現類 BaseExecutor 會有一級快取相關的邏輯,在 CachingExecutor 中會有二級快取的相關邏輯。如果直接呼叫 Statement 執行 SQL 語句,那麼在每個 Statement 的實現類中,都要寫一套一級快取和二級快取的邏輯,就顯得冗餘了。這一塊後面會細講。

  // SQL命令(在解析mybatis-config.xml配置檔案的時候生成的)
  private final SqlCommand command;
  
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    // 從command物件中獲取要執行操作的SQL語句的型別,如INSERT/UPDATE/DELETE/SELECT
    switch (command.getType()) {
      // 插入
      case INSERT: {
        // 把介面方法裡的引數轉換成sql能識別的引數
        // 如:accountMapper.selectByPrimaryKey(1)
        // 把其中的引數"1"轉化為sql能夠識別的引數
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 呼叫SqlSession執行插入操作
        // rowCountResult(): 獲取SQL語句的執行結果
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      // 更新
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 呼叫SqlSession執行更新操作
        // rowCountResult(): 獲取SQL語句的執行結果
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      // 刪除
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 呼叫SqlSession執行更新操作
        // rowCountResult(): 獲取SQL語句的執行結果
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      // 查詢
      case SELECT:
        // method.returnsVoid(): 返參是否為void
        // method.hasResultHandler(): 是否有對應的結果處理器
        if (method.returnsVoid() && method.hasResultHandler()) {
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) { // 查詢多條記錄
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) { // 查詢結果返參為Map
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) { // 以遊標的方式進行查詢
          result = executeForCursor(sqlSession, args);
        } else {
          // 引數轉換 轉成sqlCommand引數
          Object param = method.convertArgsToSqlCommandParam(args);
          // 執行查詢 查詢單條資料
          result = sqlSession.selectOne(command.getName(), param);
          if (method.returnsOptional()
              && (result == null || !method.getReturnType().equals(result.getClass()))) {
            result = Optional.ofNullable(result);
          }
        }
        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;
  }

 

在上面,有多處出現這樣一行程式碼:
method.convertArgsToSqlCommandParam (args),該方法的作用就是將方法引數轉換為 SqlCommandParam;具體交由
paramNameResolver.getNamedParams () 實現。在看 paramNameResolver.getNamedParams () 之前,我們先來看下 paramNameResolver 是什麼東西?

    public Object convertArgsToSqlCommandParam(Object[] args) {
      return paramNameResolver.getNamedParams(args);
    }

 

在前面,我們在例項化 MethodSignature 物件 (new MethodSignature) 的時候,在其構造方法中,會例項化 ParamNameResolver 物件,該物件主要用來處理介面形式的引數,最後會把引數處放在一個 map(即屬性 names)中。map 的 key 為引數的位置,value 為引數的名字。

public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
  ...
  this.paramNameResolver = new ParamNameResolver(configuration, method);
}

 

對 names 欄位的解釋:

假設在 xxxMapper 中有這麼一個介面方法 selectByIdAndName ()

・selectByIdAndName (@Param ("id") String id, @Param ("name") String name) 轉化為 map 為 {{0, "id"}, {1, "name"}}

・selectByIdAndName (String id, String name) 轉化為 map 為 {{0, "0"}, {1, "1"}}

・selectByIdAndName (int a, RowBounds rb, int b) 轉化為 map 為 {{0, "0"}, {2, "1"}}

 

構造方法的會經歷如下的步驟

1. 透過反射得到方法的引數型別和方法的引數註解註解,
method.getParameterAnnotations () 方法返回的是註解的二維陣列,每一個方法的引數包含一個註解陣列。

2. 遍歷所有的引數

- 首先判斷這個引數的型別是否是特殊型別,RowBounds 和 ResultHandler,是的話跳過,我們不處理

- 判斷這個引數是否是用來 Param 註解,如果使用的話 name 就是 Param 註解的值,並把 name 放到 map 中,鍵為引數在方法中的位置,value 為 Param 的值

- 如果沒有使用 Param 註解,判斷是否開啟了 UseActualParamName,如果開啟了,則使用 java8 的反射得到方法的名字,此處容易造成異常,

具體原因參考上一篇博文.

- 如果以上條件都不滿足的話,則這個引數的名字為引數的下標

  // 通用key字首,因為key有param1,param2,param3等;
  public static final String GENERIC_NAME_PREFIX = "param";
  // 存放引數的位置和對應的引數名
  private final SortedMap<Integer, String> names;
  // 是否使用@Param註解
  private boolean hasParamAnnotation;

  public ParamNameResolver(Configuration config, Method method) {
    // 透過註解得到方法的引數型別陣列
    final Class<?>[] paramTypes = method.getParameterTypes();
    // 透過反射得到方法的引數註解陣列
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    // 用於儲存所有引數名的SortedMap物件
    final SortedMap<Integer, String> map = new TreeMap<>();
    // 引數註解陣列長度,即方法入參中有幾個地方使用了@Param
    // 如selectByIdAndName(@Param("id") String id, @Param("name") String name)中,paramCount=2
    int paramCount = paramAnnotations.length;
    // 遍歷所有的引數
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      // 判斷這個引數的型別是否是特殊型別,RowBounds和ResultHandler,是的話跳過
      if (isSpecialParameter(paramTypes[paramIndex])) {
        continue;
      }
      String name = null;
      for (Annotation annotation : paramAnnotations[paramIndex]) {
        // 判斷這個引數是否使用了@Param註解
        if (annotation instanceof Param) {
          // 標記當前方法使用了Param註解
          hasParamAnnotation = true;
          // 如果使用的話name就是Param註解的值
          name = ((Param) annotation).value();
          break;
        }
      }
      // 如果經過上面處理,引數名還是null,則說明當前引數沒有指定@Param註解
      if (name == null) {
        // 判斷是否開啟了UseActualParamName
        if (config.isUseActualParamName()) {
          // 如果開啟了,則使用java8的反射得到該引數對應的屬性名
          name = getActualParamName(method, paramIndex);
        }
        // 如果name還是為null
        if (name == null) {
          // use the parameter index as the name ("0", "1", ...)
          // 使用引數在map中的下標作為引數的name,如 ("0", "1", ...)
          name = String.valueOf(map.size());
        }
      }
      // 把引數放入到map中,key為引數在方法中的位置,value為引數的name(@Param的value值/引數對應的屬性名/引數在map中的位置下標)
      map.put(paramIndex, name);
    }
    // 最後使用Collections工具類的靜態方法將結果map變為一個不可修改型別
    names = Collections.unmodifiableSortedMap(map);
  }

 

getNamedParams(): 該方法會將引數名和引數值對應起來,並且還會額外儲存一份以 param 開頭加引數順序數字的值

 public Object getNamedParams(Object[] args) {
    // 這裡的names就是ParamNameResolver中的names,在構造ParamNameResolver物件的時候,建立了該Map
    // 獲取方法引數個數
    final int paramCount = names.size();
    // 沒有引數
    if (args == null || paramCount == 0) {
      return null;
    // 只有一個引數,並且沒有使用@Param註解。
    } else if (!hasParamAnnotation && paramCount == 1) {
      // 直接返回,不做任務處理
      return args[names.firstKey()];
    } else {
      // 包裝成ParamMap物件。這個物件繼承了HashMap,重寫了get方法。
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      // 遍歷names中的所有鍵值對
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        // 將引數名作為key, 對應的引數值作為value,放入結果param物件中
        param.put(entry.getValue(), args[entry.getKey()]);
        // 用於新增通用的引數名稱,按順序命名(param1, param2, ...)
        final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
        // 確保不覆蓋以@Param 命名的引數
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
  }
}  

 

getNamedParams () 總結:

1. 當只有一個引數的時候,直接返回,不做任務處理;

2. 否則,存入 Map 中,鍵值對形式為:paramName=paramValue

・selectByIdAndName (@Param ("id") String id, @Param ("name") String name): 傳入的引數是 ["1", "張三"],最後解析出來的 map 為:{“id”:”1”,”“name”:” 張三”}

・selectByIdAndName (String id, @Param ("name") String name): 傳入的引數是 ["1", "張三"],最後解析出來的 map 為:{“param1”:”1”,”“name”:” 張三”}

 

假設執行的 SQL 語句是 select 型別,繼續往下看程式碼

在 mapperMethod.execute (), 當
convertArgsToSqlCommandParam () 方法處理完方法引數後,假設我們此時呼叫的是查詢單條記錄,那麼接下來會執行 sqlSession.selectOne () 方法。

 

sqlSession.selectOne () 原始碼分析:

sqlSession.selectOne () 也是調的 sqlSession.selectList () 方法,只不過只返回 list 中的第一條資料。當 list 中有多條資料時,拋異常。

@Override
public <T> T selectOne(String statement, Object parameter) {
  // 呼叫當前類的selectList方法
  List<T> list = this.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;
  }
}

 

sqlSession.selectList () 方法

  @Override
  public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

 

繼續看:

 @Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      // 從Configuration裡的mappedStatements里根據key(id的全路徑)獲取MappedStatement物件
      MappedStatement ms = configuration.getMappedStatement(statement);
      // 呼叫Executor的實現類BaseExecutor的query()方法
      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();
    }
  }

 

在 sqlSession.selectList () 方法中,我們可以看到呼叫了 executor.query (),假設我們開啟了二級快取,那麼 executor.query () 呼叫的是 executor 的實現類 CachingExecutor 中的 query (),二級快取的邏輯就是在 CachingExecutor 這個類中實現的。

 

關於 mybatis 二級快取:

二級快取預設是不開啟的,需要手動開啟二級快取,實現二級快取的時候,MyBatis 要求返回的 POJO 必須是可序列化的。快取中儲存的是序列化之後的,所以不同的會話操作物件不會改變快取。

怎麼開啟二級快取:

<settings>
    <setting name = "cacheEnabled" value = "true" />
</settings>

 

怎麼使用二級快取?

1. 首先肯定是要開啟二級快取啦~

2. 除此之外,要使用二級快取還要滿足以下條件:

・當會話提交之後才會填充二級快取(為什麼?後面會解釋)

・SQL 語句相同,引數相同

・相同的 statementID

・RowBounds 相同

為什麼要會話提交後才會填充二級快取?

首先,我們知道,與一級快取(會話級快取)不同的是,二級快取是跨執行緒使用的,也就是多個會話可以一起使用同一個二級快取。假設現在不用提交便可以填充二級快取,我們看看會存在什麼問題?

假設會話二現在對資料庫進行了修改操作,修改完進行了查詢操縱,如果不用提交就會填充二級快取的話,這時候查詢操作會把剛才修改的資料填充到二級快取中,如果此時剛好會話一執行了查詢操作,便會查詢到二級快取中的資料。如果會話二最終回滾了剛才的修改操作,那麼會話一就相當於發生了髒讀。

Mybatis原始碼解析之執行SQL語句

 

實際上,查詢的時候會填充快取,只不過此時是填充在暫存區,而不是填充在真正的二級快取區中。而上面所說的要會話提交後才會填充二級快取,指的是將暫存區中的快取刷到真正的二級快取中。啊???那不對呀,填充在暫存區,那此時會話一來查詢,豈不是還會從暫存區中取到快取,從而導致髒讀?別急,接著往下看。

對於查詢操作,每次取快取都是從真正的二級快取中取快取,而不是從暫存區中取快取。

 

好了,我們接著看原始碼~

CachingExecutor.query () 原始碼:

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    // 獲取要執行的sql語句 sql語句在解析xml的時候就已經解析好了
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 生成二級快取key
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    // 呼叫過載方法
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

 

呼叫過載方法:query ()

 @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    // 獲取mybatis的二級快取配置<cache>
    Cache cache = ms.getCache();
    // 如果配置了二級快取
    if (cache != null) {
      // 是否要重新整理快取,是否手動設定了需要清空快取
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        // 從二級快取中獲取值
        List<E> list = (List<E>) tcm.getObject(cache, key);
        // 從二級快取中取不到值
        if (list == null) {
          // 交由delegate查詢 這裡的delegate指向的是BaseExecutor
          // BaseExecutor中實現了一級快取的相關邏輯
          // 也就是說,當在二級快取中獲取不到值的時候,會從一級快取中獲取,一級快取要是還是獲取不到
          // 才會去查詢資料庫
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          // 將查詢結果存放在暫存區中,只有會話提交後才會將資料刷到二級快取,避免髒讀問題
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

 

接著,我們看下 BaseExecutor.query () 是怎麼實現一級快取邏輯的:

@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());
    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;
  }

 

當從一級快取中獲取不到資料時,會查資料庫:

呼叫
BaseExecutor.queryFromDatabase()

 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;
  }

 

呼叫 BaseExecutor.doQuery ():在 BaseExecutor 中,doQuery () 只是個抽象方法,具體交由子類實現:

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

 

從前面的流程中可知,在每次執行 CURD 的時候,都需要獲取 SqlSession 這個物件,介面如下:

可以看出來這個介面主要定義類關於 CRUD、資料庫事務、資料庫重新整理等相關操作。下面看它的預設實現類:

Mybatis原始碼解析之執行SQL語句

 

可以看到 DefaultSqlSession 實現了 SqlSession 中的方法,(其實我們自己也可根據需要去實現)。而在 DefaultSqlSession 類中有一個很重要的屬性,就是 Mybatis 的執行器(Executor)。

Executor 介紹:

Executor 執行器,是 mybatis 中執行查詢的主要程式碼,Executor 分為三種:

・簡單執行器 SimpleExecutor

・可重用執行器 ReuseExecutor

・批次執行器 BatchExecutor

預設使用的執行器是 SimpleExecutor,可以在 mybatis 的配置檔案中設定使用哪種執行器

public class Configuration {
    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
}

 

 

Executor 類圖:

Mybatis原始碼解析之執行SQL語句

 

假設我們使用的就是預設的執行器,SimpleExecutor。我們來看下 SimpleExecutor.doQuery ()

 @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    // 這裡就進入jdbc了
    Statement stmt = null;
    try {
      // 獲取核心配置物件
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      //預編譯SQL語句
      stmt = prepareStatement(handler, ms.getStatementLog());
      // 執行查詢
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    // 獲取連線 這裡的連線是代理連線
    Connection connection = getConnection(statementLog);
    // 預編譯
    stmt = handler.prepare(connection, transaction.getTimeout());
    // 給預編譯sql語句設定引數
    handler.parameterize(stmt);
    return stmt;
  }

 

在上面的原始碼中,我們可以看到 StatementHandler,它是用來幹嘛的?

在 mybatis 中,透過 StatementHandler 來處理與 JDBC 的互動,我們看下 StatementHandler 的類圖:

Mybatis原始碼解析之執行SQL語句

 

可以看出,跟 Executor 的繼承實現很像,都有一個 Base,Base 下面又有幾個具體實現子類,很明顯,採用了模板模式。不同於 CacheExecutor 用於二級快取之類的實際作用,這裡的 RoutingStatementHandler 僅用於維護三個 Base 子類的建立與呼叫。

 

•BaseStatementHandler

・SimpleStatementHandler:JDBC 中的 Statement 介面,處理簡單 SQL 的

・CallableStatementHandler:JDBC 中的 PreparedStatement,預編譯 SQL 的介面

・PreparedStatementHandler:JDBC 中的 CallableStatement,用於執行儲存過程相關的介面

・RoutingStatementHandler:路由三個 Base 子類,負責其建立及呼叫

 

 public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    switch (ms.getStatementType()) {
      // 策略模式:根據不同語句型別 選用不同的策略實現類
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }
  }

 

嗯,很眼熟的策略模式,按照 statementType 的值來決定返回哪種 StatementHandler。

那這裡的 statementType 是在哪裡賦值的呢?我們看下 MappedStatement 的構造方法:

public Builder(Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) {
      ...
      // 構造方法中預設取值為PREPARED
      mappedStatement.statementType = StatementType.PREPARED;
      ...
    }

 

如果不想使用的 StatementType.PREPARED,怎麼自定義呢?

(1) 在 xxxMapper.xml 中:可以透過 <select /> 的 statementType 屬性指定

<select id="getAll" resultType="Student2" statementType="CALLABLE">
    SELECT * FROM Student
</select>

 

(2) 如果採用的是註解開發:透過 @SelectKey 的 statementType 屬性指定

@SelectKey(keyProperty = "account", 
        before = false, 
        statementType = StatementType.STATEMENT, 
        statement = "select * from account where id = #{id}", 
        resultType = Account.class)
Account selectByPrimaryKey(@Param("id") Integer id);

 

到此,select 型別的 SQL 語句就基本執行完畢了,我們來總結一下 mybatis

MyBatis 的主要的核心部件有以下幾個:

SqlSession:作為 MyBatis 工作的主要頂層 API,表示和資料庫互動的會話,完成必要資料庫增刪改查功能;

Executor:MyBatis 執行器,是 MyBatis 排程的核心,負責 SQL 語句的生成和查詢快取的維護;

StatementHandler:封裝了 JDBC Statement 操作,負責對 JDBC statement 的操作,如設定引數、將 Statement 結果集轉換成 List 集合。

ParameterHandler:負責對使用者傳遞的引數轉換成 JDBC Statement 所需要的引數;

ResultSetHandler:負責將 JDBC 返回的 ResultSet 結果集物件轉換成 List 型別的集合;

TypeHandler:負責 java 資料型別和 jdbc 資料型別之間的對映和轉換;

MappedStatement:MappedStatement 維護了一條 <select|update|delete|insert> 節點的封裝;

SqlSource:負責根據使用者傳遞的 parameterObject,動態地生成 SQL 語句,將資訊封裝到 BoundSql 物件中,並返回;

BoundSql:表示動態生成的 SQL 語句以及相應的引數資訊;

Configuration:MyBatis 所有的配置資訊都維持在 Configuration 物件之中;

Mybatis原始碼解析之執行SQL語句

 

Mybatis原始碼解析之執行SQL語句

相關文章