Mybatis源码解析(二) —— 加载 Configuration

Mybatis源码解析(二) —— 加载 Configuration

   正如上文所看到的 Configuration 对象保存了所有Mybatis的配置信息,也就是说mybatis-config.xml 以及 mapper.xml 中的所有信息
都可以在 Configuration 对象中获取到。所以一般情况下,Configuration 对象只会存在一个。通过上篇文章我们知道了mybatis-config.xml 和 mapper.xml
分别是通过 XMLConfigBuilder 和 XMLMapperBuilder 进行解析存储到Configuration的。但有2个问题需要我们去了解:

  • 1、 XMLConfigBuilder 和 XMLMapperBuilder 是如何解析xml信息的?
  • 2、 Configuration 内部结构是怎样的?它是如何存储 xml信息的?

   那么,我们就带着这2个问题去分析下源码吧!

一、 Configuration 属性

  Configuration包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

  • configuration

    • properties(属性)
    • settings(设置)
    • typeAliases(类型别名)
    • typeHandlers(类型处理器)
    • objectFactory(对象工厂)
    • plugins(插件)
    • environments(环境配置)

      • environment(环境变量)
      • transactionManager(事务管理器)
      • dataSource(数据源)
    • databaseIdProvider(数据库厂商标识)
    • mappers(映射器)

  其中我们最常配置的是 settings 。一个配置相对完整的 settings 元素的示例如下:



  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

   查看 Configuration 源码,我们可以轻松的找到上面配置对应的字段属性:


   protected Environment environment;
 
   protected boolean safeRowBoundsEnabled = false;
   protected boolean safeResultHandlerEnabled = true;
   protected boolean mapUnderscoreToCamelCase = false;
   protected boolean aggressiveLazyLoading = true;
   protected boolean multipleResultSetsEnabled = true;
   protected boolean useGeneratedKeys = false;
   protected boolean useColumnLabel = true;
   protected boolean cacheEnabled = true;
   protected boolean callSettersOnNulls = false;
   protected String logPrefix;
   protected Class  logImpl;
   protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
   protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
   protected Set lazyLoadTriggerMethods = new HashSet(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
   protected Integer defaultStatementTimeout;
   protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
   protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
 
   protected Properties variables = new Properties();
   protected ObjectFactory objectFactory = new DefaultObjectFactory();
   protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
   protected MapperRegistry mapperRegistry = new MapperRegistry(this);
 
   protected boolean lazyLoadingEnabled = false;
   protected ProxyFactory proxyFactory;
 
   protected String databaseId;
   
   protected Class configurationFactory;
 
   protected final InterceptorChain interceptorChain = new InterceptorChain();
   protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
   protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
   protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();

   上面的字段属性对应的是mybatis-config.xml 配置文件,那么对应mapper.xml的字段属性如下:


  protected final Map mappedStatements = new StrictMap("Mapped Statements collection");
  protected final Map caches = new StrictMap("Caches collection");
  protected final Map resultMaps = new StrictMap("Result Maps collection");
  protected final Map parameterMaps = new StrictMap("Parameter Maps collection");
  protected final Map keyGenerators = new StrictMap("Key Generators collection");
  
  protected final Map sqlFragments = new StrictMap("XML fragments parsed from previous mappers");

  其中 我们最需要关注的是 mappedStatementsresultMaps 以及 sqlFragments

  • resultMaps: 不难理解就是 保存了 mapper.xml 中的 resultMap 节点信息
  • mappedStatements: 保存了 Mapper 配置文件中得 select/update/insert/delete节点信息
  • sqlFragments: 保存了 Mapper 配置文件中得 sql 节点信息

  上面3种是我们在平时项目开发中使用最多的,我们可以发现其 都是 StrictMap 这个 内部类 的 value,那我们来具体分析下 StrictMap 与普通Map有什么不一样的地方:

    public V put(String key, V value) {
      if (containsKey(key))
        throw new IllegalArgumentException(name + " already contains value for " + key);
      if (key.contains(".")) {
        final String shortKey = getShortName(key);
        if (super.get(shortKey) == null) {
          // 存简称 key
          super.put(shortKey, value);
        } else {
          // 重复的 key 时存的value 为  Ambiguity ,在 get 时会判断  value 是否为 Ambiguity,是则抛异常
          super.put(shortKey, (V) new Ambiguity(shortKey));
        }
      }
      // 存全称 key
      return super.put(key, value);
    }
    
    public V get(Object key) {
      V value = super.get(key);
      if (value == null) {
        throw new IllegalArgumentException(name + " does not contain value for " + key);
      }
      // 判断类型是否为 Ambiguity
      if (value instanceof Ambiguity) {
        throw new IllegalArgumentException(((Ambiguity) value).getSubject() + " is ambiguous in " + name
            + " (try using the full name including the namespace, or rename one of the entries)");
      }
      return value;
    }
        
   
    // 截取最后一个"."符号后面的字符串做为shortName
    private String getShortName(String key) {
      final String[] keyparts = key.split("\\.");
      final String shortKey = keyparts[keyparts.length - 1];
      return shortKey;
    }    
    

   从源码中我们可以看出,其重写了 put 和 get 2个方法 ,其中 put方法针对 key 做了3个方面的处理:

  • 1、 截取最后一个"."符号后面的字符串做为 key 存储一次value
  • 2、 key 重复时,存储的value是一个 Ambiguity 对象。get 获取时会判断value是否未 Ambiguity 类型,如果是则抛出异常
  • 3、 直接调用 super.put(key, value) 存储同一 value 一次(此时key未做任何操作处理)

   也就是说,针对 :

    StrictMap.put("com.xxx.selectId","select * from user where id=?")

   这一次put请求, StrictMap 中有 2个不同的key,但value相同的元素:


  com.xxx.selectId = select * from user where id=?
          selectId = select * from user where id=?
          

  以上就是 Configuration 内部属性的大致分析,其中关键的属性分别是: mappedStatementsresultMapssqlFragments,接下来我们会分析这3。

二、 XMLConfigBuilder.parse()

   XMLConfigBuilder.parse() 主要用于解析mybatis-config.xml 配置文件的信息,其本身没有多大的意义去分析,我这边还是给出部分源码吧,有想进一步去了解的同学可以自行深入分析:


  public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  private void parseConfiguration(XNode root) {
    try {
      // 解析 properties(参数配置) 节点
      propertiesElement(root.evalNode("properties"));
      // 解析 typeAliases(别名) 节点
      typeAliasesElement(root.evalNode("typeAliases"));
      // 解析 plugins(插件) 节点
      pluginElement(root.evalNode("plugins"));
      // 解析 objectFactory(数据库返回结果集使用) 节点
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      // 解析 settings 节点
      settingsElement(root.evalNode("settings"));
      // 解析 environments 节点
      environmentsElement(root.evalNode("environments")); 
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      // 解析 mappers 节点
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

三、 XmlMapperBuilder.parse()

   如果拿电脑做比喻的话,前面 XMLConfigBuilder.parse() 就好比主机,但是仅仅有主机是不行的,我们还得需要鼠标、键盘、显示器等等组件才玩组装成一个完整的电脑。而 XmlMapperBuilder.parse() 所做的事儿就是组装各种组件(Mapper)。我们来看下 XmlMapperBuilder.parse() 的源码:


  public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
      // 解析方法源头
      configurationElement(parser.evalNode("/mapper"));
      configuration.addLoadedResource(resource);
      bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingChacheRefs();
    parsePendingStatements();
  }

  // 最核心解析方法
  private void configurationElement(XNode context) {
    try {
      // 我们都知道 Mapper 的  namespace 是与 Mapper接口路径对应的,所以进来需要判断下 namespace
      String namespace = context.getStringAttribute("namespace");
      if (namespace.equals("")) {
          throw new BuilderException("Mapper's namespace cannot be empty");
      } 
      // 为 MapperBuilderAssistant 设置 namespace
      builderAssistant.setCurrentNamespace(namespace);
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      // 解析 resultMap 节点信息
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      // 解析 sql 节点信息
      sqlElement(context.evalNodes("/mapper/sql"));
      // 解析 select|insert|update|delete 节点信息
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
    }
  }

   我们可以看到核心的解析方法内部分别针对 不同的节点 进行加载,我们先看下 resultMap 的解析加载:

加载 resultMap节点

   正如官方所描述的一样 : resultMap 是最复杂也是最强大的元素(用来描述如何从数据库结果集中来加载对象)。 所以其解析复杂度也是最复杂的,我们先看一个简单的resultMap 节点配置:



  
  
  

  结合中上面的配置, 我们再看下面其解析源码会更加清晰明了:


  private ResultMap resultMapElement(XNode resultMapNode, List additionalResultMappings) throws Exception {
    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
    // 获取 resultMap 节点中的 id 配置信息,也就是上面示列的  id="selectUserById"
    String id = resultMapNode.getStringAttribute("id",
        resultMapNode.getValueBasedIdentifier());
    // 获取 resultMap 节点中的 type 配置信息,也就是上面示列的  type="User"
    String type = resultMapNode.getStringAttribute("type",
        resultMapNode.getStringAttribute("ofType",
            resultMapNode.getStringAttribute("resultType",
                resultMapNode.getStringAttribute("javaType"))));
    String extend = resultMapNode.getStringAttribute("extends");
    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
    Class typeClass = resolveClass(type);
    Discriminator discriminator = null;
    List resultMappings = new ArrayList();
    resultMappings.addAll(additionalResultMappings);
    // 获取到所有字节的信息,即 id 节点、result节点等等
    List resultChildren = resultMapNode.getChildren();
    for (XNode resultChild : resultChildren) {
      if ("constructor".equals(resultChild.getName())) {
        processConstructorElement(resultChild, typeClass, resultMappings);
      } else if ("discriminator".equals(resultChild.getName())) {
        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
      } else {
        ArrayList flags = new ArrayList();
        if ("id".equals(resultChild.getName())) {
          flags.add(ResultFlag.ID);
        }
        // 将获取到的 子节点信息封装到 resultMapping 对象中。
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
      }
    }
    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
    try {
      // 实际调用的是 MapperBuilderAssistant.addResultMap() 方法
      return resultMapResolver.resolve();
    } catch (IncompleteElementException  e) {
      configuration.addIncompleteResultMap(resultMapResolver);
      throw e;
    }
  }

   从源码分析来看,整个解析流程分4步走:

  • 1、 获取 resultMap 节点中的 id 配置信息,也就是上面示列的 id="blogPostResult"
  • 2、 获取 resultMap 节点中的 type 配置信息,也就是上面示列的 type="User" ( Class 名)
  • 3、 将获取到的 子节点信息封装到 resultMapping 对象中。
  • 4、 实际调用的是 MapperBuilderAssistant.addResultMap() 方法 将上面3步获取到的数据生成 resultMap 保存到 Configuration 中。

   上面有2 个关键对象: ResultMappingMapperBuilderAssistant。其中 MapperBuilderAssistant 贯穿了整个Mapper的解析,所以先不分析,我们先看下 ResultMapping ,其源码内部的字段属性有以下:

ResultMapping 类属性

  private Configuration configuration;
  private String property;
  private String column;
  private Class javaType;
  private JdbcType jdbcType;
  private TypeHandler typeHandler;
  private String nestedResultMapId;
  private String nestedQueryId;
  private Set notNullColumns;
  private String columnPrefix;
  private List flags;
  private List composites;
  private String resultSet;
  private String foreignColumn;
  private boolean lazy;

ResultMap 类属性

  private String id;
  private Class type;
  private List resultMappings;
  private List idResultMappings;
  private List constructorResultMappings;
  private List propertyResultMappings;
  private Set mappedColumns;
  private Discriminator discriminator;
  private boolean hasNestedResultMaps;
  private boolean hasNestedQueries;
  private Boolean autoMapping;

   相信大多数同学对其中的 property、column、javaType、jdbcType、typeHandler 这几个相对熟悉很多,正如看到的一样 ResultMapping 主要用于封装 resultMap 节点的所有子节点(子节点嵌套也是一样的) 的 信息。它与 ResultMap 的关系如下:

  • 1、 ResultMap 是由 id、type以及大量的 ResultMapping 对象 组合而成。
  • 2、 ResultMapping对象 是 结果集(数据库操作结果集)与 java Bean对象 属性的 对应关系。 即一个 ResultMapping对象 对应一个 Bean 对象中某个字段属性。
  • 3、 ResultMap 对象是 结果集 与 java Bean对象的 对应关系。即一个 ResultMap 对象 对应一个 Bean对象。

加载 select|insert|update|delete节点

   我们先看一个简单的 select 节点元素的配置:


   我们再来分析下 其实如何被加载的, 我们来分析下 加载这4个节点的方法 buildStatementFromContext() 源码:


  private void buildStatementFromContext(List list, String requiredDatabaseId) {
    for (XNode context : list) {
      // 创建 XMLStatementBuilder 
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
        // 通过 XMLStatementBuilder的 parseStatementNode() 方法进行加载。
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }

   我们可以看到其内部创建了一个 XMLStatementBuilder 对象,然后再调用其 parseStatementNode() 进行加载的。仔细发现,我们可以看到创建 XMLStatementBuilder 对象需要 的3跟 关系构造参数:configuration、 builderAssistant(是不是很熟悉,没错就是 MapperBuilderAssistant ) 、context(节点信息)

XMLStatementBuilder.parseStatementNode()

   parseStatementNode() 方法是加载 select|insert|update|delete节点 信息的核心,那么我们深入分析其内部实现:

   // 省略了一些相对不重要的代码
   public void parseStatementNode() {
    
    // 以下几个获取的配置信息,我们都应该很熟悉吧
    String id = context.getStringAttribute("id");
    String parameterMap = context.getStringAttribute("parameterMap");
    String parameterType = context.getStringAttribute("parameterType");
    Class parameterTypeClass = resolveClass(parameterType);
    String resultMap = context.getStringAttribute("resultMap");
    String resultType = context.getStringAttribute("resultType");
    Class resultTypeClass = resolveClass(resultType);

    
    // 读取  信息 
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());


    // 将每个
        select 
            stud_id as studId, name, phone
        from students
        
            name = #{name}
            
                AND phone = #{phone}
            
        
        


  

   正如上面的sql一样,如果我们一次性把SQL保存到一个 SqlNode 中,那是不是在获取生成 BoundSql 时 解析相对困难了呢?如果我们把一些关键点给做个分割是不是相对好解析点呢?所以出现了 IfSqlNode、WhereSqlNode等等,不用看,大家应该也能明白 IfSqlNod 就是用于 存储 :

            
                AND phone = #{phone}
            

   当然不是直接存储的,大致结构可以看下图:

   我们获取 BoundSql 时 IfSqlNode 就会判断 是否满足条件。所以整个 SqlNode 体系是很庞大的,它们分别有不同的职责。从上面我们看到最后将 SqlNode 作为 创建 DynamicSqlSource 对象的参数。 我们来查看下 DynamicSqlSource 源码。看看其是如何获取到 BoundSql的:

public class DynamicSqlSource implements SqlSource {

  private Configuration configuration;
  // 存放了SQL片段信息
  private SqlNode rootSqlNode;

  public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) {
    this.configuration = configuration;
    this.rootSqlNode = rootSqlNode;
  }

  public BoundSql getBoundSql(Object parameterObject) {
    DynamicContext context = new DynamicContext(configuration, parameterObject);
    // 每个SqlNode的 apply方法调用时,都将解析好的sql加到context中,最终通过context.getSql()得到完整的sql 
    rootSqlNode.apply(context);
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
    SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    for (Map.Entry entry : context.getBindings().entrySet()) {
      boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
    }
    return boundSql;
  }

}

   正如上面所示一样, 每个SqlNode都会取调用 apply方法 自行解析并拼接到context。可能有人会问,getBoundSql() 什么时候会被调用呢? 我这里提前 解释下: 当我们请求Mapper接口时(即一个SqlSession会话访问数据库时)会调用到。

   BoundSql 内部主要时封装好了请求sql,以及请求参数,这是其源码内部属性:

  // 一个完整的sql,此时的sql 就是 JDBC 那种,即  select * from user where id = ?
  private String sql; 
  // 参数列表
  private List parameterMappings;
  private Object parameterObject;
  private Map additionalParameters;
  private MetaObject metaParameters;

   至此, 加载 select|insert|update|delete节点 的流程已经非常清晰了。但我们还有一个 MapperBuilderAssistant 没解析。其实 MapperBuilderAssistant 类如其,它就是 MapperBuilderXml 的 助理。
MapperBuilderXml 对象负责从XML读取配置,而 MapperBuilderAssistant 负责创建对象并加载到Configuration中。

四、个人总结

   整个 Configuration 的加载主要分2部分:

  • 1、 mybatis-config.xml 的加载
  • 2、 mapper.xml 的加载

  其中 mapper.xml 的加载 是 最为复杂的,本文也主要解析了它的加载。下面的序列图讲述其加载流程:

         如果您对这些感兴趣,欢迎star、follow、收藏、转发给予支持!

本文由博客一文多发平台 OpenWrite 发布!

你可能感兴趣的:(java)