MyBatis源码解析

Mybatis源码详解 基于3.5.10的版本对Mybatis源码从加载到执行全流程的解析,通过与传统JDBC方法的对比更深一步的了解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

Mybatis入门到源码解析 MyBatis是一款优秀的基于Java的持久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身,而不需要花费精力去处理加载驱动、创建连接、创建Statement等繁杂的过程。持久化持久化是将程序数据在持久状态和瞬时状态间转换的机制。(理解一下这个持久状态转化为瞬时状态,持久化是mybatis最重要的特性)即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等。 阅读详情

相关推荐

深入解析MyBatis源码与实战

摘要:本文系统解析MyBatis核心架构与实现原理,涵盖配置解析、SQL执行、结果映射三大模块。通过动态SQL生成、缓存机制(一级/二级缓存)、插件开发(Interceptor接口)等典型示例,深入剖析源码实现。结合SpringBoot集成场景,展示CRUD操作、动态SQL拼接、事务管理、多数据源配置等实战方案,并给出批量操作优化(BatchExecutor)、类型处理器扩展等高级特性实现。特别说明流程图关键节点:从SqlSessionFactory构建到Executor执行,通过StatementHand

keny-大成的博客 1365

MyBatis-3.4.2-源码分析15:XML解析之buildStatementFromContext(context.evalNodes(‘select|insert|update|delete’...

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34242658的博客 324

深入 MyBatis-Spring 源码解析 ——揭秘 MyBatis 与 Spring 的完美融合

当谈到 Java 的持久层框架,MyBatis 几乎总会出现在讨论中;它轻量、灵活,非常适合需要复杂 SQL 查询的场景。而我们的大管家 Spring,除了帮我们管理依赖和控制反转之外,还可以跟 MyBatis 完美地配合在一起!这就是我们今天要讨论的主题——。在这个分析中,我们将通过源码来揭秘 MyBatis-Spring 是如何在两者间架起桥梁的,希望让你对其工作原理有一个深入的理解。MyBatis-Spring 是 Spring 提供的一个适配器模块,它的目标是帮助开发者在 Spring 应用中。

喵手的博客 2022

Mybatis 核心源码分析

一、Mybatis 整体执行流程 二、Mybatis 层次结构 三、源码分析

Julie的博客 1万+

怒肝一夜 | Mybatis源码深度解析

关注“Java后端技术全栈”回复“面试”获取全套面试资料本文:12006字,阅读时长:10分15秒前面已经发过Mybatis源码解析的文章了,本文是对前面文章进行精简以及部分调整优化,总...

田维常 1326

【DaVinci Developer实战指南】从入门到精通:软件组件设计与配置全解析

本文详细解析了DaVinci Developer在汽车电子开发中的核心应用,从软件组件设计到配置实战,涵盖Application SWC创建、RunnableEntity设计及Exclusive Area配置等关键环节。通过实际案例分享,帮助开发者快速掌握AUTOSAR架构下的ECU软件开发技巧,提升工作效率与系统稳定性。

weixin_30952535的博客 249

Mybatis解析(二)

Mybatis解析二第七部分:Mybatis缓存7.1 ⼀级缓存7.2 ⼆级缓存 第七部分:Mybatis缓存 7.1 ⼀级缓存 ①、在⼀个sqlSession中,对User表根据id进⾏两次查询,查看他们发出sql语句的情况 @Test public void test1(){ //根据 sqlSessionFactory 产⽣ session SqlSession sqlSession = sessionFactory.openSession(); UserMapper userMapper = sql

weixin_43380444的博客 981

用Django框架+爬虫技术实现自动获取可画(Canva)团队会员资格的方法

可画(canva)是一个非常流行的在线平面设计平台,因为它无需专业训练和技能就可以利用其丰富的资源设计出美观、酷炫的作品,因而它受到了极其广泛的设计专业和非专业人群的喜爱本文介绍了一种方法,它采用Django网络框架与爬虫技术相结合,实时监控定时更新可画团队版免费邀请链接的网站页面,一旦链接有更新动作,第一时间获取相关信息,并直接加载这个有效的邀请链接,自动进入可画网站获得团队版使用资格。

hhyyqq的博客 2208

mybatis源码解析

mybatis底层代码分析

weixin_43189971的博客 3813

FPGA—ZYNQ_BD Block Design学习(一)

1.第一步:打开Vivado软件,创建或打开一个工程。2.第二步:在Block Design中添加arm核心,并将其配置为IP核。3.第三步:配置arm核心的外设信息,如DDR接口、时钟频率、UART接口等。4.第四步:完成Block Design中的模块互联,生成PL端的比特流。 5.第五步:导出PS端的硬件信息,包括arm IP核的外设、速度、引脚和地址等信息。1创建bd 需要有ddr以及uart和时钟配置外设io口,这里就是zynq的管脚规定好的,根据原理图用哪个个勾选哪一个。 对外设uart的配

m0_58129662的博客 1028

Foxglove Studio实战:5步搞定自动驾驶数据可视化(附避坑指南)

本文详细介绍了如何使用Foxglove Studio高效搭建自动驾驶数据可视化工作流。通过五个核心步骤:环境准备、数据导入、面板搭建、交互分析与自动化集成,帮助开发者快速掌握这一专为机器人系统设计的开源平台。文章重点解析了其与ROS/ROS 2、MCAP等数据源的无缝对接,以及3D点云、多传感器融合、团队标注等核心功能,并附有实用的性能优化与避坑指南,旨在提升算法调试与团队协作效率。

d3e4f的博客 336

mybatis源码解析-xml文件的解析

mybatis源码解析xml文件的流程

m0_54258715的博客 1286

正负数据如何归一化_生信干货 | LC-MS代谢组学QI软件下机数据代谢物筛选和归一化如何做?...

上海·2019第一届多层组学前言技术发展华东区客户研讨会倒计时1天LC-MS非靶向代谢组学数据下机啦~~拿到一堆数据怎么办?不会高端代码,也不会自己写脚本,我怎么处理数据?​本期小编带来了LC-MS非靶向代谢组学下机数据处理实用干货,包括:下机定性结果表格的解析、代谢物筛选如何做?以及定量数据如何做归一化?实用干货,赶紧来抢~~话不多说,赶紧来学习吧~~非靶向LC-MS代谢组学的分析流程LC-MS...

weixin_36441329的博客 2983

Mybatis源码解析

Mybatis是支持定制化SQL、存储过程和高级映射的持久层框架。主要完成两件事: 封装JDBC的操作 利用反射完成Java类和SQL之间的转换 mybatis的主要目的就是管理执行SQL是参数的输入和输出,编写SQL和结果集的映射是mybatis的主要优点 mybatis中主要类和接口 Configuration:将mybatis配置文件中的信息保存到该类中 SqlSessionFac...

一点点的积累 7112

YOLOv11 改进 - 注意力机制 | LS-YOLO MSFE 多尺度特征提取模块:并行分支结构增强多尺度感知,优化遥感与小目标检测

本文介绍了一种用于滑坡检测的模型LS-YOLO及其在YOLOv11中的结合应用。LS-YOLO首先构建多尺度滑坡数据集MSLD,为模型训练提供丰富数据。设计了基于高效通道注意力、平均池化和空间可分离卷积的多尺度特征提取模块MSFE,充分提取滑坡特征信息。在解耦头中采用膨胀卷积增加模型感受野。我们将MSFE模块集成进YOLOv11,替换部分原有模块。实验表明,改进后的YOLOv11在数据集中表现出色 。

魔改工程师的博客 870

数据库系统工程师软考备战:第三篇 - SQL语言深入解析与应用

​​创建表​​​修改表​​​删除表​。

Programming Talk 122

Mybatis的源码解析

要想解析源码,我们首先要知道什么是Mybatis 一、Mybatis的介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。 MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。 ...

qq_43667317的博客 554

Multisim14.0仿真应用设计(十六)74LS138译码器应用仿真

74LS138为3线-8线译码器。

zhusl6688的博客 2982

mybatis -源码解析

mybatis -源码解析 一、mybatis 核心 接口 Configration : 管理 mybatis-config.xml 全局配置关系类 SqlSessionFactory :session管理工厂 接口 SqlSession :SqlSession是面向用户操作数据库的接口,提供了很多操作数据库...

distance_power的博客 309

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Mybatis运行原理及源码解析

Mybatis源码解析 一、前言 本文旨在mybatis源码解析,将整个mybatis运行原理讲解清楚,本文代码地址: https://github.com/lchpersonal/mybatis-learn 本文使用的mybatis版本:3.2.8, jdk版本:1.8 数据库版本:mysql 5.6,数据库脚本如下,此外在源文件为:resources/mybatis.sql -- 导出 myb...

拨开云雾看世界 1万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

MyBatis框架源码解析

MyBatis是一个优秀的持久层框架,通过简洁的XML配置方式就能消除以前传统 使用JDBC出现大量重复的代码,以及参数的设置和结果集的映射. 如果能够懂的底层代码和原理,在使用上就会更得心应手。而且出现错误,也能更快的找出错误的原因。解析源码 还有个好处,就是能够看一下大神的设计思想。这些设计思想也可以运用到实际开发中,而且如果自己明白框架怎么写之后,自己也可以尝试去写一个开源框架出来; 同时,...

ITsource 264

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Mybatis3 源码解析系列

Mybatis作为一个优秀的Java持久化框架,在我们的日常工作中相信都会用到,本次源码解析系列,就开始探索下Mybatis

github_35735591的博客 1076

Mybatis源码深度解析

Mybatis源码深度解析

weixin_43785662的博客 165

【Mybatis】动态 SQL 源码解析

动态SQL解析原理 我们在使用mybatis的时候,会在xml中编写sql语句。比如这段动态sql代码: <update id="update" parameterType="org.format.dynamicproxy.mybatis.bean.User"> UPDATE users <trim prefix="SET" prefixOverrides=","> <if test="name != null and name != ''"&g

菜鸡也有大佬梦 880

源码 解析_mybatis源码详解,配置解析包源码阅读:配置解析概述

配置解析包源码阅读配置解析包用来实现 MyBatis 配置文件、映射文件的解析等工作,并最终为 MyBatis 准备好进行数据库操作的运行环境。在本篇中,我们将对 MyBatis 中配置解析包的源码进行阅读,了解 MyBatis 是如何完成配置的解析工作的。在此过程中,也会总结相关的源码阅读技巧。配置解析概述许多应用需要在进行一定的配置之后才能使用,MyBatis也不例外。在 1.5.2节我们已经...

weixin_30611317的博客 209
上一篇: Github上被疯传的Redis实战文档也太香了
下一篇: 深入理解Raft算法
java架构师小芷
博客等级 码龄6年 216粉丝 519原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值