MyBatis源码解析

一、使用

首先我们在看源码之前要学会使用MyBatis,我们先看下使用的示例,代码大概长这样:

@Test
public void test() throws Exception {
    // 读取配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream("resources/sqlMapConfig.xml");
    // 通过SqlSessionFactoryBuilder创建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    // 获取到SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 调用Mapper中的指定方法 com.wyh.mapper.UserMapper.queryAll是statementId
    List<User> userList = sqlSession.selectList("com.wyh.mapper.UserMapper.queryAll");
    System.out.println(userList);
}
复制代码

二、读取配置文件并转换成InputStream流

/**
 * 使用classLoader将文件读取成文件输入流
 * Returns a resource on the classpath as a Stream object
 *
 * @param loader   The classloader used to fetch the resource
 * @param resource The resource to find
 * @return The resource
 * @throws java.io.IOException If the resource cannot be found or read
 */
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
  InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
  if (in == null) {
    throw new IOException("Could not find resource " + resource);
  }
  return in;
}
复制代码

三、 创建SqlSessionFactory

通过SqlSessionFactoryBuilder创建SqlSessionFactory

public SqlSessionFactory build(InputStream inputStream) {
    // 调用重载方法
    return build(inputStream, null, null);
}

/**
 * 解析MyBatis配置文件方法
 *
 * @param inputStream 配置文件流
 * @param environment 环境名称
 * @param properties 配置属性
 * @return SqlSessionFactory
 */
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  try {
    // 创建用来解析sqlMapConfig.xml配置的XMLConfigBuilder
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    // parser.parse()方法是解析sqlMapConfig.xml中的配置
    // build()方法构建DefaultSqlSessionFactory
    return build(parser.parse());
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  } finally {
    ErrorContext.instance().reset();
    try {
      inputStream.close();
    } catch (IOException e) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}
复制代码

3.1 解析配置文件

在解析配置文件时使用了XMLConfigBuilder,XMLConfigBuilder是用来解析MyBatis的sqlMapConfig.xml的,和它类似的还有XMLMapperBuilder、XMLStatementBuilder....他们的父类都是BaseBuilder,这些类都是用来解析各种不同的配置

继续看代码,下面调用了XMLConfigBuilder.parse方法

public Configuration parse() {
    // 判断是否解析过
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    // 将解析状态标为已解析
    parsed = true;
    // 解析configuration下的配置
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
}
复制代码

parse方法中又调用了parseConfiguration()方法解析标签下的内容,这个方法会解析properties、settings、typeAliases、mapper....这些标签

private void parseConfiguration(XNode root) {
    try {
      // 解析properties标签
      // issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      // 解析settings标签
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      // 加载自定义vfsImpl
      loadCustomVfs(settings);
      // 加载自定义logImpl
      loadCustomLogImpl(settings);
      // 解析typeAliases标签
      typeAliasesElement(root.evalNode("typeAliases"));
      // 解析plugins标签
      pluginElement(root.evalNode("plugins"));
      // 解析objectFactory标签
      objectFactoryElement(root.evalNode("objectFactory"));
      // 解析objectWrapperFactory标签
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      // 解析reflectorFactory标签
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // 解析environments标签
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      // 解析databaseIdProvider标签
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      // 解析typeHandlers标签
      typeHandlerElement(root.evalNode("typeHandlers"));
      // 解析mapper标签
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
}
复制代码

3.2 解析properties

private void propertiesElement(XNode context) throws Exception {
  if (context != null) {
    Properties defaults = context.getChildrenAsProperties();
    // 获取resource
    String resource = context.getStringAttribute("resource");
    // 获取url属性
    String url = context.getStringAttribute("url");
    // resource 和 url 不能同时存在
    if (resource != null && url != null) {
      throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
    }
    if (resource != null) {
      // 将获取到的resource都放到defaults这个类中
      defaults.putAll(Resources.getResourceAsProperties(resource));
    } else if (url != null) {
      // 将从url获取到的properties属性都放到defaults类中
      defaults.putAll(Resources.getUrlAsProperties(url));
    }
    // 获取configuration中的配置
    Properties vars = configuration.getVariables();
    if (vars != null) {
      defaults.putAll(vars);
    }
    parser.setVariables(defaults);
    // 把解析到的properties再放回configuration中
    configuration.setVariables(defaults);
  }
}
复制代码

3.3 解析typeAliases

typeAliases主要是为了在配置mapperXml中parameterType和resultType是可以不适用全限定命名而使用配置的别名

先看下typeAliases配置:

<typeAliases>
        <!-- 针对单个别名定义 type:类型的路径 alias:别名 -->
        <!-- <typeAlias type="cn.wyh.entity.User" alias="user"/> -->

        <!-- 批量别名定义指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
        <package name="com.wyh.entity"/>
</typeAliases>
复制代码

typeAliasesElement方法主要是用来解析typeAliases标签中内容的

private void typeAliasesElement(XNode parent) {
  if (parent != null) {
    // 循环所有子节点
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        // 获取包名
        String typeAliasPackage = child.getStringAttribute("name");
        // 扫描所有包下的类,然后注册到Configuration.typeAliasRegistry
        configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
      } else {
        // 获取别名
        String alias = child.getStringAttribute("alias");
        // 获取类型
        String type = child.getStringAttribute("type");
        try {
          Class<?> clazz = Resources.classForName(type);
          if (alias == null) {
            // 根据类名注册到Configuration.typeAliasRegistry
            typeAliasRegistry.registerAlias(clazz);
          } else {
            // 根据配置好的别名alias注册到Configuration.typeAliasRegistry
            typeAliasRegistry.registerAlias(alias, clazz);
          }
        } catch (ClassNotFoundException e) {
          throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
        }
      }
    }
  }
}
复制代码

解析完成后这些别名信息都存储在Configuration.typeAliasRegistry中,MyBatis也自带了一下别名配置,如下:

public TypeAliasRegistry() {
    registerAlias("string", String.class);
    registerAlias("byte", Byte.class);
    registerAlias("long", Long.class);
    registerAlias("short", Short.class);
    registerAlias("int", Integer.class);
    registerAlias("integer", Integer.class);
    registerAlias("double", Double.class);
    registerAlias("float", Float.class);
    registerAlias("boolean", Boolean.class);
    //...,下面还有很多,可以自己看下源码
}
复制代码

3.4 解析plugins

plugins的配置:

<plugins>
    <!-- 分页插件 -->
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <property name="dialect" value="mysql"/>
    </plugin>
    
    <!-- MyBatisPlus配置 -->
    <plugin interceptor="tk.mybatis.mapper.mapperhelper.MapperInterceptor">
        <!--指定当前通用mapper接口使用的是哪一个-->
        <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
    </plugin>
</plugins>
复制代码

pluginElement是用来解析plugins配置的,这个方法会将所有的plugins配置注册到Configuration.interceptorChain中

private void pluginElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      // 解析类名
      String interceptor = child.getStringAttribute("interceptor");
      // 解析properties属性
      Properties properties = child.getChildrenAsProperties();
      // 获取类的实例
      Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
      interceptorInstance.setProperties(properties);
      // 将Interceptor注册到Configuration.interceptorChain中
      configuration.addInterceptor(interceptorInstance);
    }
  }
}
复制代码

3.5 解析typeHandlers

typeHandlers配置信息:

<typeHandlers>
  <typeHandler handler="com.wyh.util.ExampleTypeHandler" javaType="java.util.Date" jdbcType="VARCHAR"/></typeHandlers>
复制代码

typeHandlerElement这个方法会根据配置的javaType和jdbcType做对应然后注册到Configuration.typeHandlerRegistry中

/**
 * 解析typeHandlers配置
 * @param parent
 */
private void typeHandlerElement(XNode parent) {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                // 获取配置好的包名
                String typeHandlerPackage = child.getStringAttribute("name");
                // 寻找包下的所有类,然后扫描类中的注解得到javaTypeClass 和 jdbcType
                typeHandlerRegistry.register(typeHandlerPackage);
            } else {
                // 获取java类型
                String javaTypeName = child.getStringAttribute("javaType");
                // 获取 java类型对应的jdbc类型
                String jdbcTypeName = child.getStringAttribute("jdbcType");
                // 获取 handlerTypeName
                String handlerTypeName = child.getStringAttribute("handler");
                Class<?> javaTypeClass = resolveClass(javaTypeName);
                JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
                Class<?> typeHandlerClass = resolveClass(handlerTypeName);
                if (javaTypeClass != null) {
                    if (jdbcType == null) {
                        // 注册到typeHandlerRegistry中
                        typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
                    } else {
                        // 注册到typeHandlerRegistry中
                        typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
                    }
                } else {
                    // 注册到typeHandlerRegistry中
                    typeHandlerRegistry.register(typeHandlerClass);
                }
            }
        }
    }
}
复制代码

3.6 解析mapper

基本配置我们都看过了,现在我们来看下主要的mapper映射文件是怎么解析的,mapperElement方法是用来解析mapper映射文件的,代码如下:

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // 配置是某个包下所有的类
        if ("package".equals(child.getName())) {
          // 获取包的名称
          String mapperPackage = child.getStringAttribute("name");
          // 将包下的所有类都注册到Configuration.mapperRegistry中
          configuration.addMappers(mapperPackage);
        }
        // 配置了单个的资源文件
        else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          // 解析resource配置
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            // 获取资源文件流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 通过XMLMapperBuilder来解析该文件
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,        configuration.getSqlFragments());
            mapperParser.parse();
          }
          // 解析url资源
          else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            // 获取资源文件流
            InputStream inputStream = Resources.getUrlAsStream(url);
            // 通过XMLMapperBuilder来解析该文件
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          }
          // 解析mapperClass资源
          else if (resource == null && url == null && mapperClass != null) {
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
}
复制代码

3.6.1 XMLMapperBuilder.parse

XMLMapperBuilder对象是用来解析mapper.xml的,他的父类是BaseBuilder,我们下面看下它是怎么解析的:

public void parse() {
  // 判断该资源是否被加载过
  if (!configuration.isResourceLoaded(resource)) {
    // 加载mapper映射文件
    configurationElement(parser.evalNode("/mapper"));
    // 将资源加入被加载列表
    configuration.addLoadedResource(resource);
    bindMapperForNamespace();
  }

  parsePendingResultMaps();
  parsePendingCacheRefs();
  parsePendingStatements();
}

// 解析mapper标签下的内容
private void configurationElement(XNode context) {
  try {
    // 获取namespace属性
    String namespace = context.getStringAttribute("namespace");
    if (namespace == null || namespace.isEmpty()) {
      throw new BuilderException("Mapper's namespace cannot be empty");
    }
    builderAssistant.setCurrentNamespace(namespace);
    cacheRefElement(context.evalNode("cache-ref"));
    cacheElement(context.evalNode("cache"));
    // 解析parameterMap
    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
    // 解析resultMap
    resultMapElements(context.evalNodes("/mapper/resultMap"));
    // 解析sql片段
    sqlElement(context.evalNodes("/mapper/sql"));
    // 解析select|insert|update|delete标签 最终将标签内容解析成MappedStatement并添加到Configuration.mappedStatements中
    buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  }
}
复制代码

3.6.1.1 buildStatementFromContext方法

buildStatementFromContext方法是用来解析mapper.xml中sql的配置:

private void buildStatementFromContext(List<XNode> list) {
  if (configuration.getDatabaseId() != null) {
    buildStatementFromContext(list, configuration.getDatabaseId());
  }
  buildStatementFromContext(list, null);
}

private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
  for (XNode context : list) {
    // 创建XMLStatementBuilder
    final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
    try {
      statementParser.parseStatementNode();
    } catch (IncompleteElementException e) {
      configuration.addIncompleteStatement(statementParser);
    }
  }
}
复制代码

调用statementParser.parseStatementNode()方法进行解析;

public void parseStatementNode() {
    // 方法的id
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
      return;
    }
    // 标签的名字<select|insert|update|delete>
    String nodeName = context.getNode().getNodeName();
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
    // 判断是否是查询语句
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    // XML中的SQL片段
    // Include Fragments before parsing
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    // 获取parameterType
    String parameterType = context.getStringAttribute("parameterType");
    // 根据parameterType名称先去别名配置typeAliasRegistry中查找,如果没有则使用反射获得该类
    Class<?> parameterTypeClass = resolveClass(parameterType);

    String lang = context.getStringAttribute("lang");
    LanguageDriver langDriver = getLanguageDriver(lang);

    // Parse selectKey after includes and remove them.
    processSelectKeyNodes(id, parameterTypeClass, langDriver);

    // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    if (configuration.hasKeyGenerator(keyStatementId)) {
      keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
          ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
    }

    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    // 获取statementType 执行Sql时会用
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    // 返回类型
    String resultType = context.getStringAttribute("resultType");
    Class<?> resultTypeClass = resolveClass(resultType);
    // 返回Map类型
    String resultMap = context.getStringAttribute("resultMap");
    // 获取resultSetType 映射sql返回结果时会用
    String resultSetType = context.getStringAttribute("resultSetType");
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
    if (resultSetTypeEnum == null) {
      resultSetTypeEnum = configuration.getDefaultResultSetType();
    }
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");
    String resultSets = context.getStringAttribute("resultSets");

    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
        resultSetTypeEnum, flushCache, useCache, resultOrdered,
        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
复制代码

再statementParser.parseStatementNode()方法中调用了builderAssistant.addMappedStatement方法,将解析到的属性都封装成stamentMap然后存放到Configuration.mappedStatements中

public MappedStatement addMappedStatement(
      String id,
      SqlSource sqlSource,
      StatementType statementType,
      SqlCommandType sqlCommandType,
      Integer fetchSize,
      Integer timeout,
      String parameterMap,
      Class<?> parameterType,
      String resultMap,
      Class<?> resultType,
      ResultSetType resultSetType,
      boolean flushCache,
      boolean useCache,
      boolean resultOrdered,
      KeyGenerator keyGenerator,
      String keyProperty,
      String keyColumn,
      String databaseId,
      LanguageDriver lang,
      String resultSets) {

    if (unresolvedCacheRef) {
      throw new IncompleteElementException("Cache-ref not yet resolved");
    }

    id = applyCurrentNamespace(id, false);
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;

    MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
        .resource(resource)
        .fetchSize(fetchSize)
        .timeout(timeout)
        .statementType(statementType)
        .keyGenerator(keyGenerator)
        .keyProperty(keyProperty)
        .keyColumn(keyColumn)
        .databaseId(databaseId)
        .lang(lang)
        .resultOrdered(resultOrdered)
        .resultSets(resultSets)
        .resultMaps(getStatementResultMaps(resultMap, resultType, id))
        .resultSetType(resultSetType)
        .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
        .useCache(valueOrDefault(useCache, isSelect))
        .cache(currentCache);

    ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
    if (statementParameterMap != null) {
      statementBuilder.parameterMap(statementParameterMap);
    }

    MappedStatement statement = statementBuilder.build();
    configuration.addMappedStatement(statement);
    return statement;
}
复制代码

3.7 解析完毕

当这些配置文件都解析完成后配置信息都存放到了Configuration这个对象中,Configuration就是myBatis的数据中心。

我们回过头再看SqlSessionFactoryBuilder.build()方法

/**
 * 解析MyBatis配置文件方法
 *
 * @param inputStream 配置文件流
 * @param environment 环境名称
 * @param properties 配置属性
 * @return SqlSessionFactory
 */
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  try {
    // 创建用来解析sqlMapConfig.xml配置的XMLConfigBuilder
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    // parser.parse()方法是解析sqlMapConfig.xml中的配置
    // build()方法构建DefaultSqlSessionFactory
    return build(parser.parse());
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  } finally {
    ErrorContext.instance().reset();
    try {
      inputStream.close();
    } catch (IOException e) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}


public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}
复制代码

builder方法会根据Configuration对象构建一个DefaultSqlSessionFactory,至此构建SqlSessionFactory就构建完毕了

四、获取SqlSession

因为SqlSessionFactoryBuilder返回的是DefaultSqlSession,所以openSession这个方法也在DefaultSqlSession中

@Override
public SqlSession openSession() {
  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    // 获取配置文件中配置的数据库环境
    final Environment environment = configuration.getEnvironment();
    // 根据数据库环境构建TransactionFactory
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    // 构建Transaction
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    // 构建executor 此时execType=null, 那默认构建的是SimpleExecutor
    final Executor executor = configuration.newExecutor(tx, execType);
    // 返回DefaultSqlSession
    return new DefaultSqlSession(configuration, executor, autoCommit);
  } catch (Exception e) {
    closeTransaction(tx); // may have fetched a connection so lets call close()
    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}
复制代码

五、执行指定Sql

我们想调用mapper.xml中指定sql的话需要调用sqlSession.selectOne 或者 selectList 方法,传入的参数是mapper.xml.namespace + 标签ID,因为在上面解析标签时是按照这个格式存储的,实例代码:

List<User> userList = sqlSession.selectList("com.wyh.mapper.UserMapper.queryAll");
复制代码

DefaultSqlSession.selectList

@Override
public <E> List<E> selectList(String statement) {
  return this.selectList(statement, 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 {
    // 根据statementId获取MappedStatement
    MappedStatement ms = configuration.getMappedStatement(statement);
    // 调用SimpleExecutor的父类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();
  }
}
复制代码

BaseExecutor.query

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

@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 {
    // 执行simpleExecutor.doQuery方法
    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;
}
复制代码

SimpleExecutor.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();
      // 这里会返回PreparedStatementHandler
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      // 给sql中的参数赋值
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }
复制代码

preparedStatementHandler.query

@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  PreparedStatement ps = (PreparedStatement) statement;
  // 执行sql语句
  ps.execute();
  // 封装返回结果
  return resultSetHandler.handleResultSets(ps);
}
复制代码

至此MyBatis的一套执行流程就解析完了。

总结

MyBatis 的执行流程

SqlSessionFactoryBuilder -> DefaultSqlSessionFactory -> DefaultSqlSession -> SimpleExecutor -> PreparedStatementHandler -> ResultSetHandler

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值