1. 程式人生 > >深入原始碼分析mybatis查詢原理(四)

深入原始碼分析mybatis查詢原理(四)

由於前面幾篇的查詢都是沒有帶引數的,那麼我現在加一個帶引數查詢的方法,來看一下mybatis如何處理引數並查詢。

EmpTexst.java  t1()方法

Emp emp = empmapper.queryByEmpNoAndName(1, "admin");
System.out.println(emp);

empmapper.java

//按條件查詢
    Emp queryByEmpNoAndName(@Param("empNo") int empNo, @Param("name") String name);
empmapper.xml
<select id="queryByEmpNoAndName" resultType="emp">
	    select * from emp where EMPNO = #{empNo} and ENAME = #{name}
	</select>

以上就是增加的查詢

在Emp emp = empmapper.queryByEmpNoAndName(1, "admin");打上斷點。

進入原始碼

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

重點關注mapperMethod.execute(sqlSession, args); 前面方法都討論過了,今天接著討論這個方法

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

這個execute方法會根據執行SQL的型別和返回結果的型別選擇合適的sql執行,這個查詢將會執行

Object param = method.convertArgsToSqlCommandParam(args);

 result = sqlSession.selectOne(command.getName(), param);


可以看到這裡的引數列表[1,admin]。

斷點進入 convertArgsToSqlCommandParam 這個方法,從這個方法名字可以知道,這個方法的作用是將引數列表轉換為SQL的引數。原始碼

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

這裡看到有一個 paramNameResolver 物件,ParamNameResolver類是用來對方法的引數做解析的,解析的過程是在建立 MethodSignature 物件時解析的,由於上一章方法沒有引數,所以引數解析也就沒有討論到,現在給它補上,不好意思,這樣子就有點亂了。那我們回顧一下 MethodSignature 建立過程吧

public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
      Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
      if (resolvedReturnType instanceof Class<?>) {
        this.returnType = (Class<?>) resolvedReturnType;
      } else if (resolvedReturnType instanceof ParameterizedType) {
        this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
      } else {
        this.returnType = method.getReturnType();
      }
      this.returnsVoid = void.class.equals(this.returnType);
      this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray());
      this.returnsCursor = Cursor.class.equals(this.returnType);
      this.mapKey = getMapKey(method);
      this.returnsMap = (this.mapKey != null);
      this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
      this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
      this.paramNameResolver = new ParamNameResolver(configuration, method);
    }
可以看到最後一段程式碼  this.paramNameResolver = new ParamNameResolver(configuration, method);之前的分析,包括

MethodSignature是什麼,何時建立都在上一章討論過了,這裡不再重複囉嗦了。好,我們點進去看看ParamNameResolver的建立過程。

ParamNameResolver 建立

public ParamNameResolver(Configuration config, Method method) {
    final Class<?>[] paramTypes = method.getParameterTypes();
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
    int paramCount = paramAnnotations.length;
    // get names from @Param annotations
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      if (isSpecialParameter(paramTypes[paramIndex])) {
        // skip special parameters
        continue;
      }
      String name = null;
      for (Annotation annotation : paramAnnotations[paramIndex]) {
        if (annotation instanceof Param) {
          hasParamAnnotation = true;
          name = ((Param) annotation).value();
          break;
        }
      }
      if (name == null) {
        // @Param was not specified.
        if (config.isUseActualParamName()) {
          name = getActualParamName(method, paramIndex);
        }
        if (name == null) {
          // use the parameter index as the name ("0", "1", ...)
          // gcode issue #71
          name = String.valueOf(map.size());
        }
      }
      map.put(paramIndex, name);
    }
    names = Collections.unmodifiableSortedMap(map);
  }

解讀一下這段程式碼:首先,通過java的反射獲取到引數的型別和引數的註解method.getParameterAnnotations()方法返回的是註解的二維陣列,每一個方法的引數包含一個註解陣列。 



到這裡,停一下,這個引數註解是個二維陣列,那麼這個二維陣列是怎麼排列組合的呢,引數註解的length和引數型別陣列的length有什麼關係?

看上面的圖知道,paramAnnotations[0][0] = @org.apache.ibatis.annotations.Param(value=name),

paramAnnotations[1][0] = @org.apache.ibatis.annotations.Param(value=name),也就是說二維陣列是包含多個僅有一個值的陣列.因為引數前可以新增多個註解,所以是二維陣列,一個引數上不可以新增相同的註解,同一個註解可以加在不同的引數上!

而這個一維陣列的length就是引數陣列的length,如果一個引數沒有加註解,一個引數加了註解,會是怎麼樣的呢,我們改一下程式碼。

empmapper.java
//按條件查詢
    Emp queryByEmpNoAndName(int empNo, @Param("name") String name);
empmapper.xml
<select id="queryByEmpNoAndName" resultType="emp">
	    select * from emp where EMPNO = #{0} and ENAME = #{name}
	</select>

再次斷點進入,檢視


可以看到第一個是空,第二個沒有區別。

好,回到主線上,mybatis通過反射獲取到引數型別陣列和註解陣列後,遍歷所有的引數 ,判斷這個引數的型別是否是特殊型別,這裡特殊型別指RowBounds和ResultHandler,是的話跳過,咱不處理 ,然後判斷這個引數是否是用來Param註解,如果使用的話,設定hasParamAnnotation為true,表示引數中使用了Param註解,然後設定name就是Param註解的值,把name放到map中,鍵為引數在方法中的位置,value為Param的值 ,如果沒有使用Param註解,判斷是否開啟了UseActualParamName,如果開啟了,則使用java8的反射得到方法的名字。如果沒有開啟,那麼就會使用引數索引作為name。

這個討論的有點,亂舉個例子,mybatis通過建立ParamNameResolver時對引數做解析。解析的結果:

Emp queryByEmpNoAndName(int empNo, @Param("name") String name);

解析結果:{0=0, 1=name}

Emp queryByEmpNoAndName(@Param("empNo") int empNo, @Param("name") String name);

解析結果:{0=empNo, 1=name}

Emp queryByEmpNoAndName(@Param("empNo") int empNo, String name);

解析結果:{0=empNo, 1=1}

好了,我們回到paramNameResolver.getNamedParams(args);接著往下討論


public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    if (args == null || paramCount == 0) {
      return null;
    } else if (!hasParamAnnotation && paramCount == 1) {
      return args[names.firstKey()];
    } else {
      final Map<String, Object> param = new ParamMap<Object>();
      int i = 0;
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        param.put(entry.getValue(), args[entry.getKey()]);
        // add generic param names (param1, param2, ...)
        final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
        // ensure not to overwrite parameter named with @Param
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
  }

解讀這段程式碼,首先如果只有一個引數,就返回這個引數,否者的話就是遍歷names,取出Map的value作為引數param的key,根據names的key作為索引,從args中取出值作為引數names的value.接著生成引數 names(格式就是,param+i ,生成為param1,param2,param3.....)作為param的key,並把args作為值,若args 為 [1, admin]。那這一步生成的param就是{param1=1, param2=admin}。

可能這麼說有點不清晰,還是把上面的例子拿過來。

args 為 [1, admin]。

Emp queryByEmpNoAndName(int empNo, @Param("name") String name);

names 為 {0=0, 1=name}

解析結果:{0=1, name=admin, param1=1, param2=admin}

Emp queryByEmpNoAndName(@Param("empNo") int empNo, @Param("name") String name);

解析結果:name=admin, empNo=1, param1=1, param2=admin}

Emp queryByEmpNoAndName(@Param("empNo") int empNo, String name);

解析結果:{1=admin, empNo=1, param1=1, param2=admin}

至此 把引數列表解析成SQL引數討論完成。

接著回到這段程式碼:

Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);

selectOne方法

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

接著定位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 {
      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();
    }
  }

接續 query方法

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

首先 獲取 BoundSql ,這是什麼呢?

/**
 *    Copyright 2009-2016 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.mapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.session.Configuration;

/**
 * An actual SQL String got form an {@link SqlSource} after having processed any dynamic content.
 * The SQL may have SQL placeholders "?" and an list (ordered) of an parameter mappings 
 * with the additional information for each parameter (at least the property name of the input object to read 
 * the value from). 
 * </br>
 * Can also have additional parameters that are created by the dynamic language (for loops, bind...).
 *
 * @author Clinton Begin
 */
public class BoundSql {

  private String sql;
  private List<ParameterMapping> parameterMappings;
  private Object parameterObject;
  private Map<String, Object> additionalParameters;
  private MetaObject metaParameters;

  public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
    this.sql = sql;
    this.parameterMappings = parameterMappings;
    this.parameterObject = parameterObject;
    this.additionalParameters = new HashMap<String, Object>();
    this.metaParameters = configuration.newMetaObject(additionalParameters);
  }

  public String getSql() {
    return sql;
  }

  public List<ParameterMapping> getParameterMappings() {
    return parameterMappings;
  }

  public Object getParameterObject() {
    return parameterObject;
  }

  public boolean hasAdditionalParameter(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    String indexedName = prop.getIndexedName();
    return additionalParameters.containsKey(indexedName);
  }

  public void setAdditionalParameter(String name, Object value) {
    metaParameters.setValue(name, value);
  }

  public Object getAdditionalParameter(String name) {
    return metaParameters.getValue(name);
  }
}

英文好的同學 可以看看這段:

/**
 * An actual SQL String got form an {@link SqlSource} after having processed any dynamic content.
 * The SQL may have SQL placeholders "?" and an list (ordered) of an parameter mappings 
 * with the additional information for each parameter (at least the property name of the input object to read 
 * the value from). 
 * </br>
 * Can also have additional parameters that are created by the dynamic language (for loops, bind...).
 *
 * @author Clinton Begin
 */

這個物件有三個屬性很重要:

  private String sql; //從解析時可以看出這個sql不是配置檔案中的sql,這個sql已經經過了處理(如:佔用位符的處理、動態語句的解析if、foreach等待)
  private List<ParameterMapping> parameterMappings; //sql對應的引數列表(包含了引數名,型別,jdbc型別等等)
  private Object parameterObject;//引數

接下來是建立CacheKey,這個CacheKey,使用一級快取中會用到,這個暫時不討論,寫一章專門討論快取時在討論。

接著 query

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

可以看到,首先獲取快取,根據CacheKey,從快取中獲取結果,如果沒有則,從資料庫中獲取,並把結果設定到快取中,以備後續有相同的查詢,提高效能。這需要注意的一點是之前呼叫query的Executor都是CachingExecutor,現在呼叫query的Executor是SimpleExecutor,這是一種設計模式:裝飾者模式。


好,進入SimpleExecutor的query方法,但是當我們程式碼單步進入的是BaseExecutor。

這裡程式碼多,就在裡面寫上註釋了

@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.");
    }
//如果設定重新整理快取 ,並且queryStack查詢堆疊為0,清區域性快取,再查詢(queryStack 處理遞迴呼叫)
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
 //加一,這樣遞迴呼叫到上面的時候就不會再清區域性快取了
      queryStack++;
  //嘗試根據cachekey從localCache去查
      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;
  }

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

再看  doQuery

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

跟原始碼看一下 configuration.newStatementHandler,一路點下去,看到

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 是在mapper.xml中配置的,預設為PREPARED


接著關注一下prepareStatement方法:

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }

首先獲取連線,然後獲取 PreparedStatement。我們知道myBatis是對jdbc的封裝,回想一下jdbc執行SQL的步驟吧。

1.載入驅動。 ---->> ---myBatis 配置檔案 獲取dataSource.

2.獲取資料庫連線。 ---->> --- myBatis獲取prepareStatement時


3.建立Statement。 ---->>-----上圖也說明了myBatis怎麼獲取Statement

4.準備SQL ---->> ----- myBatis 的boundSql物件封裝處理好的SQL資訊,引數資訊。

5.設定引數 ---->> ----- 看上圖程式碼,也就是這段程式碼:

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }

關注一下這段程式碼:handler.parameterize(stmt);

一路點過去

@Override
  public void setParameters(PreparedStatement ps) {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
      for (int i = 0; i < parameterMappings.size(); i++) {
        ParameterMapping parameterMapping = parameterMappings.get(i);
        if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          String propertyName = parameterMapping.getProperty();
          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
            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);
          }
          TypeHandler typeHandler = parameterMapping.getTypeHandler();
          JdbcType jdbcType = parameterMapping.getJdbcType();
          if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
          }
          try {
            typeHandler.setParameter(ps, i + 1, value, jdbcType);
          } catch (TypeException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          } catch (SQLException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          }
        }
      }
    }
  }

這段程式碼就是PreparedStatement物件設定引數。首先獲取ParameterMapping列表,這個ParameterMapping主要是做引數解析後的結果,可以看到解析出了 引數的javaType,jdbcType,mode等等。


這段程式碼中我們重點關注 那幾個if else 分支

if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          String propertyName = parameterMapping.getProperty();
          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
            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);
          }
          TypeHandler typeHandler = parameterMapping.getTypeHandler();
          JdbcType jdbcType = parameterMapping.getJdbcType();
          if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
          }
          try {
            typeHandler.setParameter(ps, i + 1, value, jdbcType);
          } catch (TypeException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          } catch (SQLException e) {
            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
          }
        }

從parameterMapping中獲取到屬性,

首先判斷這個屬性是否是額外的引數,也就是使用 <if> <foreach>的時候,mybatis自動生成的動態引數,如果是的話就從動態引數中去取值。

第二,如果這個引數是空,那麼直接返回空。

第三,如果引數是一個簡單型別,或者是註冊了typeHandler的物件型別,就直接使用引數作為返回值,最後一個是複雜物件或者是Map型別,把引數物件包裝成MetaObject,通過getValue獲取值。

之後設定引數值。

6.執行SQL語句 ---->> ---- 下邊這個 doQuery

7.處理結果集 ---->>-----

再回到 doQuery 方法 看  handler.<E>query(stmt, resultHandler);
@Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.<E> handleResultSets(ps);
  }
這個方法呼叫PreparedStatement執行SQL語句。接下來就是對結果集的處理。

如果有讀者發現我說的有不對的地方,還望大家多多指教!