MyBatis 源码解析——SQL解析

MyBatis 源码解析——SQL解析

之前就看过MyBatis源码,理解了,但没完全理解。最近用到了它的插件,又大致看了下,顺路记一下方便自己后面再看,所以前面那些解析配置的逻辑代码就不解释了,直接从SQL解析开始。话不多说,开始了。

版本是3.5.3。

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
TestMapper mapper = sqlSession.getMapper(TestMapper.class);

原生的大致是👆🏻的这个样子,inputStream是我们对MyBatis的配置,这个不解释了,就是对我们配置的信息整合。

很明显sqlSession.getMapper(TestMapper.class);这句能得到TestMapper实体类,必须使用过代理。

直接从getMapper()这个方法出发,进入DefaultSqlSession。

@Override
public <T> T getMapper(Class<T> type) {
    return configuration.getMapper(type, this);
}


public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
}

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  	// knownMappers  这个map在加载Configuration时会扫描 我们配置要扫描的包
  	// 再将包下面的mapper class 作为key,new一个MapperProxyFactory作为value。
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 返回一个动态代理的类。
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
}

点进这个mapperProxyFactory里看看。

1. 生成代理对象

public class MapperProxyFactory<T> {
  // 这个就是TestMapper 的class,在 new MapperProxyFactory 时设置。
  private final Class<T> mapperInterface;
  // mapper 里方法的缓存,后面会涉及到
  private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();
}

public T newInstance(SqlSession sqlSession) {
  // 将这些作为参数传给MapperProxy
  final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
  return newInstance(mapperProxy);
}

// 新建一个mapper的代理类
protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

OK,这里比较简单,不详细讲了,只是新建一个mapper的代理类而已,点进去看一下MapperProxy里的invoke,看看在执行mapper的方法之前会执行啥。

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
    // 判断调用的是不是object的原生方法,是的话直接放走。
    if (Object.class.equals(method.getDeclaringClass())) {
      return method.invoke(this, args);
    } else {
      // 先点进cachedInvoker方法看下。
      return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
    }
  } catch (Throwable t) {
    throw ExceptionUtil.unwrapThrowable(t);
  }
}

private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
    try {
      // 看看缓存中是否已经有了,有的话,就直接返回了
      MapperMethodInvoker invoker = methodCache.get(method);
      if (invoker != null) {
        return invoker;
      }

      return methodCache.computeIfAbsent(method, m -> {
        // 如果该方法是default的话
        if (m.isDefault()) {
          try {
            // 判断MethodHandles类中是否有privateLookupIn方法,该方法是java9中才有,因此分别走不同的。
            if (privateLookupInMethod == null) {
              return new DefaultMethodInvoker(getMethodHandleJava8(method));
            } else {
              return new DefaultMethodInvoker(getMethodHandleJava9(method));
            }
          } catch (IllegalAccessException | InstantiationException | InvocationTargetException
              | NoSuchMethodException e) {
            throw new RuntimeException(e);
          }
        } else {
          // 一般是会走这里的。
          return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
        }
      });
    } catch (RuntimeException re) {
      Throwable cause = re.getCause();
      throw cause == null ? re : cause;
    }
  }

总结一下上面。

  1. 在调用代理对象方法前会走invoke,如果调用的方法是Object原生的,如toString这样的,那么直接走。
  2. 不是的话,调用cachedInvoker方法从缓存中获取MapperMethodInvoker。
  3. 缓存中没有的话那么新建一个MapperMethodInvoker,通常是PlainMethodInvoker,再放进缓存中。

很常见的逻辑,肯定能看懂。

这里我们看一下MapperMethod的构造方法。

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
  //  生成一个SqlCommand,这个和SQL相关的,需要注意看一下。
  this.command = new SqlCommand(config, mapperInterface, method);
  // 生成MethodSignature,
  this.method = new MethodSignature(config, mapperInterface, method);
}

1.1 生成SqlCommand

我们点进SqlCommand构造方法。

// configuration是我略过的东西,里面有很多相关的配置信息,就当它是个黑盒。另外两个参数很明显。
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
  final String methodName = method.getName();
  final Class<?> declaringClass = method.getDeclaringClass();
  // 解析从Configuration获得方法的MappedStatement,这个类很重要,里面包含了和SQL相关的东西,
  // Configuration里面维护了相关的map,mapper class.method name 作为key,value就是MappedStatement
  // 上面就说过Configuration会事先设置好。
  MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
      configuration);
  // 检测当前方法是否有对应的 MappedStatement
  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 {
    // 设置 name 和 type 变量
    name = ms.getId();
    type = ms.getSqlCommandType();
    if (type == SqlCommandType.UNKNOWN) {
      throw new BindingException("Unknown execution method for: " + name);
    }
  }
}

1.2 生成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();
  }
  // 判断return类型是否 void、集合或数组、Cursor、Optional 等
  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.returnsOptional = Optional.class.equals(this.returnType);
  // 如果这个方法有MapKey注解, 那么这个mapKey就是注解里的value,@MapKey这个注解的作用大致是指定一个字段作为返回Map中的key
  this.mapKey = getMapKey(method);
  this.returnsMap = this.mapKey != null;
  // 如果参数列表里有RowBounds,那么获取它的位置,当然只允许有一个。
  this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
  // ResultHandler 说,俺也一样。
  this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
  // 这个里面东西比较多,点进去看看。
  this.paramNameResolver = new ParamNameResolver(configuration, method);
}

这个类顾名思义,就是方法签名的意思,和方法相关的东西都有了。

1.2.1 ParamNameResolver
public ParamNameResolver(Configuration config, Method method) {
  // 获取useActualParamName的值,默认是true,它相关的信息可以查查看。
  this.useActualParamName = config.isUseActualParamName();
  // 获取方法中参数的class
  final Class<?>[] paramTypes = method.getParameterTypes();
  // 获取参数注解
  final Annotation[][] paramAnnotations = method.getParameterAnnotations();
  final SortedMap<Integer, String> map = new TreeMap<>();
  int paramCount = paramAnnotations.length;
  
  // 遍历参数列表
  for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
    // 如果是ResultHandler或RowBounds类型的,跳过
    if (isSpecialParameter(paramTypes[paramIndex])) {
      continue;
    }
    String name = null;
    // 遍历参数上的注解
    for (Annotation annotation : paramAnnotations[paramIndex]) {
      // 如果参数注解是Param,那么name 就是@Param("")中的值
      if (annotation instanceof Param) {
        hasParamAnnotation = true;
        name = ((Param) annotation).value();
        break;
      }
    }
    if (name == null) {
      // 如果useActualParamName true,默认为true。
      if (useActualParamName) {
        // 获取参数实际名,不过必须要设置-parameters。
        name = getActualParamName(method, paramIndex);
      }
      // 如果name还是null,那么获取map的大小, 
      if (name == null) {
        name = String.valueOf(map.size());
      }
    }
    // 参数的位置作为index, name作为value。
    map.put(paramIndex, name);
  }
  names = Collections.unmodifiableSortedMap(map);
}

该方法是对方法的参数做解析,会填充一个map,参数的位置作为key,有@Param时,使用其值作为value。如果没有那么判断useActualParamName,如果还是没有,那么以map.size作为value,为啥是map.size而不是index,因为我们跳过了ResultHandler或RowBounds,也就是说,是除了这两个特殊类的实际位置

所以会像这样:

  1. aMethod(@Param(“M”) int a, @Param(“N”) int b) —— {0 ->“M”, 1 -> “N”} ,当然如果没有设置@Param,如果useActualParamName为true(3.4.1默认为true),同时设置了-parameters的话,那么就会变成 {0 ->“a”, 1 -> “b”}
  2. aMethod(int a, int b) —— {0 ->“0”, 1 -> “1”}
  3. aMethod(int a, RowBounds rb, int b) —— {0 ->“0”, 2 -> “1”}

还是比较好理解的。

2. 执行SQL

OK,让我们返回最开始的代理对象那块。

new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));

也就是这里,我们跟随MapperMethod一路走,那么点进PlainMethodInvoker的invoke,这里才是真正执行的invoke。

public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
  // mapperMethod就是我们上面讲解的生成的MapperMethod。
  return mapperMethod.execute(sqlSession, args);
}

public Object execute(SqlSession sqlSession, Object[] args) {
  Object result;
  // 让我们获取这个SQL的类型
  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);
        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;
}

四个方法里面都出现了convertArgsToSqlCommandParam这个方法,还是点进去看一下。

2.1 对用户传值进行转换

public Object convertArgsToSqlCommandParam(Object[] args) {
  // paramNameResolver在上面解释过了。
  return paramNameResolver.getNamedParams(args);
}

public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    if (args == null || paramCount == 0) {
      return null;
      // 如果没有@Param注解,同时参数只有一个
    } else if (!hasParamAnnotation && paramCount == 1) {
      // 这里解释一下为啥不是args[0], 而是names.firstKey()
      // aMethod(RowBounds rb, int a) names就会是 {1 -> "0"}
      // 如果直接使用args[0],那么就会获取到RowBounds的值
      Object value = args[names.firstKey()];
      // 判断一下是否是集合类或者数组,如果是的话,转换为ParamMap 
      return wrapToMapIfCollection(value, useActualParamName ? names.get(0) : null);
    } else {
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        // 参数的实际位置为key,参数值为value
        param.put(entry.getValue(), args[entry.getKey()]);
        // 生成param1, param2
        final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
        // 确保value里不包含param1这样的参数,避免被重写。这种情况出现在用户显式命名为@Param("param1")
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
}

感觉注释上已经说的很清楚了,convertArgsToSqlCommandParam其实就是调用paramNameResolver的getNamedParams,然后返回一个ParamMap,里面装的就是 参数名 和 参数值的映射。

让我们从衍生里返回到execute上面,插入、更新、删除差不多,就不多做解释了,我们从select开始。

2.2 查询语句

select里的if else很多,大同小异,直接挑最后的通用的selectOne解释了,点进的DefaultSqlSerssion里:

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

@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
      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是个非常重要的类,executor一般为 CachingExecutor,它是一个装饰器类,装饰SimpleExecutor,用于给SimpleExecutor增加二级缓存这个功能。这个可以从Configuration类中看到:


public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
  executorType = executorType == null ? defaultExecutorType : executorType;
  executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
  Executor executor;
  if (ExecutorType.BATCH == executorType) {
    executor = new BatchExecutor(this, transaction);
  } else if (ExecutorType.REUSE == executorType) {
    executor = new ReuseExecutor(this, transaction);
  } else {
    executor = new SimpleExecutor(this, transaction);
  }
  // 二级缓存的标志
  if (cacheEnabled) {
    // 装饰executor,这个executor默认是SimpleExecutor
    executor = new CachingExecutor(executor);
  }
  // 这里是插件相关,会另外写篇文章解释,毕竟我就是因为这个开始的。
  executor = (Executor) interceptorChain.pluginAll(executor);
  return executor;
}

so,让我们点进CachingExecutor里。

// parameterObject就是我们上面说到的ParamMap
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
  // 获取BoundSql,这个过程很复杂,后面再细讲。
  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, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List<E>) tcm.getObject(cache, key);
      if (list == null) {
        list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  // 如果没有命中,调用被装饰的类的query
  return delegate.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 {
    // 查询栈+1
    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;
}

这里我也没看很细,但是有些调用看名字大概知道意思就行,这里的缓存指的是传说中的一级缓存,OK,继续走下去看数据库查询的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,也就是SimpleExecutor里。

@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,这个下面再讲。
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    stmt = prepareStatement(handler, ms.getStatementLog());
    // 执行查询,代码我就不粘贴上来了。
    return handler.query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}

终于到了执行SQL然后去查询的这里了,一步步看下来东西还是蛮多的,不过还是挺顺的。

下面对其中一些暂时略过的东西讲解一下。

2.2.1 获取BoundSql

这块地方是CachingExecutor的query里的,BoundSql 主要是将SQL文件里的东西解析并映射成类的,如 if、where标签,这块是蛮重要的,所以简单来看下。

public BoundSql getBoundSql(Object parameterObject) {
  // 调用SqlSource的getBoundSql获取BoundSql,第一步就点题了。
  BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  if (parameterMappings == null || parameterMappings.isEmpty()) {
    boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
  }

  // check for nested result maps in parameter mappings (issue #30)
  for (ParameterMapping pm : boundSql.getParameterMappings()) {
    String rmId = pm.getResultMapId();
    if (rmId != null) {
      ResultMap rm = configuration.getResultMap(rmId);
      if (rm != null) {
        hasNestedResultMaps |= rm.hasNestedResultMaps();
      }
    }
  }

  return boundSql;
}

可以看出SqlSource 下面有许多四种类,当 SQL 配置中包含 ${}(不是 #{})占位符,或者包含if、where 等标签时,会被认为是动态 SQL,就会用 DynamicSqlSource来存储 SQL 片段,不是动态的话就使用 RawSqlSource 存储 SQL 配置信息。还有两种没去看,不过大多相同,所以随便挑个DynamicSqlSource。

@Override
public BoundSql getBoundSql(Object parameterObject) {
  DynamicContext context = new DynamicContext(configuration, parameterObject);
  // 解析 SQL 片段,并将解析结果存储到 DynamicContext 中, 
  rootSqlNode.apply(context);
  SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
  Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
  // 构建 StaticSqlSource,在此过程中将 sql 语句中的占位符 #{} 替换为问号 ? 同时为它们构建相应的 ParameterMapping
  SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
  // 调用 StaticSqlSource 的 getBoundSql 获取 BoundSql
  BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
  context.getBindings().forEach(boundSql::setAdditionalParameter);
  return boundSql;
}

rootSqlNode类型应该是MixedSqlNode,它下面是其他继承SqlNode的类的集合,然后遍历执行apply。

上面的整个流程大致是:

  1. 创建 DynamicContext
  2. 解析 SQL 片段,并将解析结果存储到 DynamicContext 中
  3. 解析 SQL 语句,构建 StaticSqlSource,再获取 BoundSql
  4. 将 DynamicContext 的 ContextMap 中的内容拷贝到 BoundSql 中

具体的感兴趣可以点进去看看怎么解析的,我这就不赘述了。

2.2.2 获取StatementHandler

讲一下上面说过SimpleExecutor的doQuery里的StatementHandler,我们可以点进Configuration的newStatementHandler

public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  // 创建RoutingStatementHandler,根据名字应该是具有路由功能的
  StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
  // 遍历插件,并应用
  statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
  return statementHandler;
}

点进RoutingStatementHandler,就是根据不同类型创建不同的StatementHandler。

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

StatementHandler后面就是去创建Statement,再去执行获取结果,这块不细讲了,直接看看是怎么获取结果的吧。

2.2.3 获取结果集合

结果的集合是ResultSetHandler这个接口,它在我当前的这个版本有且只有一个实现类DefaultResultSetHandler,那么让我们看看下面mybatis是如何将结果集给映射的吧。

public List<Object> handleResultSets(Statement stmt) throws SQLException {
  ErrorContext.instance().activity("handling results").object(mappedStatement.getId());

  final List<Object> multipleResults = new ArrayList<>();

  int resultSetCount = 0;
  // 点进去可以发现是,获取第一个结果集,其实也可以顾名思义。
  ResultSetWrapper rsw = getFirstResultSet(stmt);
  // 获取我们之前存的结果映射
  List<ResultMap> resultMaps = mappedStatement.getResultMaps();
  int resultMapCount = resultMaps.size();
  // 校验,查出来了东西,但存的结果映射啥也没有,就会抛异常了。
  validateResultMapsCount(rsw, resultMapCount);
  while (rsw != null && resultMapCount > resultSetCount) {
    ResultMap resultMap = resultMaps.get(resultSetCount);
    // 处理一下结果集。
    handleResultSet(rsw, resultMap, multipleResults, null);
    // 继续下一个。
    rsw = getNextResultSet(stmt);
    cleanUpAfterHandlingResultSet();
    resultSetCount++;
  }
  
  // 此处是和多结果集相关,不继续讲了,和上面很类似。
  String[] resultSets = mappedStatement.getResultSets();
  if (resultSets != null) {
    while (rsw != null && resultSetCount < resultSets.length) {
      ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
      if (parentMapping != null) {
        String nestedResultMapId = parentMapping.getNestedResultMapId();
        ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
        handleResultSet(rsw, resultMap, null, parentMapping);
      }
      rsw = getNextResultSet(stmt);
      cleanUpAfterHandlingResultSet();
      resultSetCount++;
    }
  }

  return collapseSingleResultList(multipleResults);
}

可以简单看下处理结果集这块。

private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
  try {
    // 还是和多结果集相关的,不涉及了。
    if (parentMapping != null) {
      handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
    } else {
      // 如果一直往前回溯,可以发现resultHandler的值是Executor.NO_RESULT_HANDLER,其实就是null。
      // 当然,我们可以实现这个接口,并实现自己的逻辑。
      // 还是进入这个默认的里面吧。
      if (resultHandler == null) {
        // 创建默认的DefaultResultHandler
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
        // 处理行数据
        handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
        multipleResults.add(defaultResultHandler.getResultList());
      } else {
        handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
      }
    }
  } finally {
    // issue #228 (close resultsets)
    closeResultSet(rsw.getResultSet());
  }
}

继续看下handleRowValues 这个方法。

public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  // 如果是嵌套的,还是不分析了。
  if (resultMap.hasNestedResultMaps()) {
    ensureNoRowBounds();
    checkResultHandler();
    handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  } else {
    // 处理简单的结果map
    handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  }
}

点进handleRowValuesForSimpleResultMap

private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
    throws SQLException {
  DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
  // 获取结果集
  ResultSet resultSet = rsw.getResultSet();
 	// 根据rowBounds.offset 定位到行
  skipRows(resultSet, rowBounds);
  // 判断是否还有更多的行
  while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
    ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null);
    // 获取结果并存储。
    Object rowValue = getRowValue(rsw, discriminatedResultMap, null);
    storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
  }
}

再点进去getRowValue看下获取结果。

private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException {
  final ResultLoaderMap lazyLoader = new ResultLoaderMap();
  // 创建结果对象
  Object rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix);
  if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
    // 创建元数据对象
    final MetaObject metaObject = configuration.newMetaObject(rowValue);
    boolean foundValues = this.useConstructorMappings;
    // 按这个名字就知道,是否进行自动结果映射
    if (shouldApplyAutomaticMappings(resultMap, false)) {
      foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
    }
    foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
    foundValues = lazyLoader.size() > 0 || foundValues;
    rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
  }
  return rowValue;
}

里面还有很多细节可以细挖,但鉴于篇幅有限,以及一些原因,这边就不再多说了,感兴趣的可以自己看看。我这里只分析了查询相关的逻辑,但其他的大体相同,感兴趣的可以自己看看。

3. 总结

MyBatis很精巧,里面运用了许多经典的设计模式,如,工厂、代理、装饰器。建造者等等。当然,我们的重点不在这些设计模式上,只是说,这些设计模式帮助MyBatis更有层次,以及更精简可扩充。而且MyBatis各个类功能比较分明,基本可贯穿整个流程的如Configuration,MappedStatement和BoundSql(当然后面两个不是真正的完全和整个流程相关),所以还是相对好看懂的。总结一下,Executor 类会创建StatementHandler、ParameterHandler、ResultSetHandler 三个对象,并且,首先使用 ParameterHandler 设置 SQL 中的占位符参数,然后使用 StatementHandler 执行SQL 语句,最后使用 ResultSetHandler 封装执行结果。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值