主頁 >  其他 > Mybatis原始碼決議之執行SQL陳述句

Mybatis原始碼決議之執行SQL陳述句

2022-12-14 06:56:06 其他

作者:鄭志杰

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 陳述句的時候的呼叫程序:

 以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 = https://www.cnblogs.com/Jcloud/p/"true" />
</settings>

 

怎么使用二級快取?

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

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

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

?SQL 陳述句相同,引數相同

?相同的 statementID

?RowBounds 相同

為什么要會話提交后才會填充二級快取?

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

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

 

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

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

 

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

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、資料庫事務、資料庫重繪等相關操作,下面看它的默認實作類:

 

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

Executor 介紹:

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

?簡單執行器 SimpleExecutor

?可重用執行器 ReuseExecutor

?批量執行器 BatchExecutor

默認使用的執行器是 SimpleExecutor,可以在 mybatis 的組態檔中設定使用哪種執行器

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

 

 

Executor 類圖:

 

假設我們使用的就是默認的執行器,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 的類圖:

 

可以看出,跟 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 物件之中;

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/539859.html

標籤:其他

上一篇:GaussDB(DWS)運維 :遇到truncate執行慢,怎么辦?

下一篇:基于zookeeper的kafka中間件

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more