和 Spring 框架 的 IoC 容器初始化 一样,Mybatis 也会通过定位、解析相应的配置文件完成自己的初始化。Mybatis 的配置文件主要有 mybatis-config.xml 核心配置文件 及一系列映射配置文件,另外,Mybatis 也会根据注解进行配置。

1 BaseBuilder

Mybatis 初始化 的主要内容是加载并解析 mybatis-config.xml 配置文件、映射配置文件以及相关的注解信息。Mybatis 的初始化入口是 SqlSessionFactoryBuilder 的 build()方法。

  1. public class SqlSessionFactoryBuilder {
  2. public SqlSessionFactory build(Reader reader) {
  3. return build(reader, null, null);
  4. }
  5. public SqlSessionFactory build(Reader reader, String environment) {
  6. return build(reader, environment, null);
  7. }
  8. public SqlSessionFactory build(Reader reader, Properties properties) {
  9. return build(reader, null, properties);
  10. }
  11. /**
  12. * build()方法 的主要实现
  13. */
  14. public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
  15. try {
  16. // SqlSessionFactory 会创建 XMLConfigBuilder对象 来解析 mybatis-config.xml配置文件
  17. // XMLConfigBuilder 继承自 BaseBuilder抽象类,顾名思义这一系的类使用了 建造者设计模式
  18. XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
  19. // 解析配置文件的内容 到 Configuration对象,根据 Configuration对象
  20. // 创建 DefaultSqlSessionFactory对象,然后返回
  21. return build(parser.parse());
  22. } catch (Exception e) {
  23. throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  24. } finally {
  25. ErrorContext.instance().reset();
  26. try {
  27. // 关闭配置文件输入流
  28. reader.close();
  29. } catch (IOException e) {
  30. // Intentionally ignore. Prefer previous error.
  31. }
  32. }
  33. }
  34. public SqlSessionFactory build(Configuration config) {
  35. return new DefaultSqlSessionFactory(config);
  36. }

BaseBuilder 中的核心字段如下:

  1. public abstract class BaseBuilder {
  2. // 保存了 Mybatis 的几乎所以核心配置信息,全局唯一
  3. protected final Configuration configuration;
  4. // 在 mybatis-config.xml 中可以通过 <typeAliases>标签 定义别名
  5. protected final TypeAliasRegistry typeAliasRegistry;
  6. // 在 mybatis-config.xml 中可以通过 <typeHandlers>标签 添加 自定义TypeHandler
  7. // TypeHandler 用于完成 JDBC数据类型 与 Java类型 的相互转换,所有的 TypeHandler
  8. // 都保存在 typeHandlerRegistry 中
  9. protected final TypeHandlerRegistry typeHandlerRegistry;
  10. public BaseBuilder(Configuration configuration) {
  11. this.configuration = configuration;
  12. this.typeAliasRegistry = this.configuration.getTypeAliasRegistry();
  13. this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();
  14. }
  15. }

BaseBuilder 中的 typeAliasRegistry 和 typeHandlerRegistry 字段 均来自于 configuration,通过 BaseBuilder 的构造方法可以看到详细内容。

2 XMLConfigBuilder

XMLConfigBuilder 是 BaseBuilder 的众多子类之一,主要负责解析 mybatis-config.xml 配置文件。它通过调用 parseConfiguration()方法 实现整个解析过程,其中,mybatis-config.xml 配置文件 中的每个节点都被封装成了一个个相应的解析方法,parseConfiguration()方法 只是依次调用了这些解析方法而已。

  1. public class XMLConfigBuilder extends BaseBuilder {
  2. // 标记是否解析过 mybatis-config.xml文件
  3. private boolean parsed;
  4. // 用于解析 mybatis-config.xml 的解析器
  5. private final XPathParser parser;
  6. // 标识 <environment>配置 的名称,默认读取 <environment>标签 的 default属性
  7. private String environment;
  8. // 创建并缓存 Reflector对象
  9. private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
  10. /**
  11. * 解析的入口,调用了 parseConfiguration() 进行后续的解析
  12. */
  13. public Configuration parse() {
  14. // parsed标志位 的处理
  15. if (parsed) {
  16. throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  17. }
  18. parsed = true;
  19. // 在 mybatis-config.xml配置文件 中查找 <configuration>节点,并开始解析
  20. parseConfiguration(parser.evalNode("/configuration"));
  21. return configuration;
  22. }
  23. private void parseConfiguration(XNode root) {
  24. try {
  25. // 根据 root.evalNode("properties") 中的值就可以知道具体是解析哪个标签的方法咯
  26. propertiesElement(root.evalNode("properties"));
  27. Properties settings = settingsAsProperties(root.evalNode("settings"));
  28. loadCustomVfs(settings);
  29. typeAliasesElement(root.evalNode("typeAliases"));
  30. pluginElement(root.evalNode("plugins"));
  31. objectFactoryElement(root.evalNode("objectFactory"));
  32. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  33. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  34. settingsElement(settings);
  35. // read it after objectFactory and objectWrapperFactory issue #631
  36. environmentsElement(root.evalNode("environments"));
  37. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  38. typeHandlerElement(root.evalNode("typeHandlers"));
  39. mapperElement(root.evalNode("mappers"));
  40. } catch (Exception e) {
  41. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  42. }
  43. }

Mybatis 中的标签很多,所以相对应的解析方法也很多,这里挑几个比较重要的标签进行分析。

2.1 解析<typeHandlers>标签

  1. private void typeHandlerElement(XNode parent) throws Exception {
  2. if (parent != null) {
  3. // 处理 <typeHandlers> 下的所有子标签
  4. for (XNode child : parent.getChildren()) {
  5. // 处理 <package> 标签
  6. if ("package".equals(child.getName())) {
  7. // 获取指定的包名
  8. String typeHandlerPackage = child.getStringAttribute("name");
  9. // 通过 typeHandlerRegistry 的 register(packageName)方法
  10. // 扫描指定包中的所有 TypeHandler类,并进行注册
  11. typeHandlerRegistry.register(typeHandlerPackage);
  12. } else {
  13. // Java数据类型
  14. String javaTypeName = child.getStringAttribute("javaType");
  15. // JDBC数据类型
  16. String jdbcTypeName = child.getStringAttribute("jdbcType");
  17. String handlerTypeName = child.getStringAttribute("handler");
  18. Class<?> javaTypeClass = resolveClass(javaTypeName);
  19. JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
  20. Class<?> typeHandlerClass = resolveClass(handlerTypeName);
  21. // 注册
  22. if (javaTypeClass != null) {
  23. if (jdbcType == null) {
  24. typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
  25. } else {
  26. typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
  27. }
  28. } else {
  29. typeHandlerRegistry.register(typeHandlerClass);
  30. }
  31. }
  32. }
  33. }
  34. }

2.2 解析<environments>标签

  1. /**
  2. * Mybatis 可以配置多个 <environment>环境,分别用于开发、测试及生产等,
  3. * 但每个 SqlSessionFactory实例 只能选择其一
  4. */
  5. private void environmentsElement(XNode context) throws Exception {
  6. if (context != null) {
  7. // 如果未指定 XMLConfigBuilder 的 environment字段,则使用 default属性 指定的 <environment>环境
  8. if (environment == null) {
  9. environment = context.getStringAttribute("default");
  10. }
  11. // 遍历 <environment>节点
  12. for (XNode child : context.getChildren()) {
  13. String id = child.getStringAttribute("id");
  14. if (isSpecifiedEnvironment(id)) {
  15. // 实例化 TransactionFactory
  16. TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
  17. // 创建 DataSourceFactory 和 DataSource
  18. DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
  19. DataSource dataSource = dsFactory.getDataSource();
  20. // 创建的 Environment对象 中封装了上面的 TransactionFactory对象 和 DataSource对象
  21. Environment.Builder environmentBuilder = new Environment.Builder(id)
  22. .transactionFactory(txFactory)
  23. .dataSource(dataSource);
  24. // 为 configuration 注入 environment属性值
  25. configuration.setEnvironment(environmentBuilder.build());
  26. }
  27. }
  28. }
  29. }

2.3 解析<databaseIdProvider>标签

Mybatis 不像 Hibernate 那样,通过 HQL 的方式直接帮助开发人员屏蔽不同数据库产品在 sql 语法 上的差异,针对不同的数据库产品, Mybatis 往往要编写不同的 sql 语句。但在 mybatis-config.xml 配置文件 中,可以通过 <databaseIdProvider> 定义所有支持的数据库产品的 databaseId,然后在映射配置文件中定义 sql 语句节点 时,通过 databaseId 指定该 sql 语句 应用的数据库产品,也可以达到类似的屏蔽数据库产品的功能。

Mybatis 初始化时,会根据前面解析到的 DataSource 来确认当前使用的数据库产品,然后在解析映射文件时,加载不带 databaseId 属性 的 sql 语句 及带有 databaseId 属性 的 sql 语句,其中,带有 databaseId 属性 的 sql 语句 优先级更高,会被优先选中。

  1. /**
  2. * 解析 <databaseIdProvider>节点,并创建指定的 DatabaseIdProvider对象,
  3. * 该对象会返回 databaseId的值,Mybatis 会根据 databaseId 选择对应的 sql语句 去执行
  4. */
  5. private void databaseIdProviderElement(XNode context) throws Exception {
  6. DatabaseIdProvider databaseIdProvider = null;
  7. if (context != null) {
  8. String type = context.getStringAttribute("type");
  9. // 为了保证兼容性,修改 type取值
  10. if ("VENDOR".equals(type)) {
  11. type = "DB_VENDOR";
  12. }
  13. // 解析相关配置信息
  14. Properties properties = context.getChildrenAsProperties();
  15. // 创建 DatabaseIdProvider对象
  16. databaseIdProvider = (DatabaseIdProvider) resolveClass(type).newInstance();
  17. // 配置 DatabaseIdProvider,完成初始化
  18. databaseIdProvider.setProperties(properties);
  19. }
  20. Environment environment = configuration.getEnvironment();
  21. if (environment != null && databaseIdProvider != null) {
  22. // 根据前面解析到的 DataSource 获取 databaseId,并记录到 configuration 的 configuration属性 上
  23. String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
  24. configuration.setDatabaseId(databaseId);
  25. }
  26. }

Mybatis 提供了 DatabaseIdProvider 接口,该接口的核心方法为 getDatabaseId(DataSource dataSource),主要根据 dataSource 查找对应的 databaseId 并返回。该接口的主要实现类为 VendorDatabaseIdProvider。

  1. public class VendorDatabaseIdProvider implements DatabaseIdProvider {
  2. private static final Log log = LogFactory.getLog(VendorDatabaseIdProvider.class);
  3. private Properties properties;
  4. @Override
  5. public void setProperties(Properties p) {
  6. this.properties = p;
  7. }
  8. @Override
  9. public String getDatabaseId(DataSource dataSource) {
  10. if (dataSource == null) {
  11. throw new NullPointerException("dataSource cannot be null");
  12. }
  13. try {
  14. return getDatabaseName(dataSource);
  15. } catch (Exception e) {
  16. log.error("Could not get a databaseId from dataSource", e);
  17. }
  18. return null;
  19. }
  20. private String getDatabaseName(DataSource dataSource) throws SQLException {
  21. // 解析到数据库产品名
  22. String productName = getDatabaseProductName(dataSource);
  23. if (this.properties != null) {
  24. // 根据 <databaseIdProvider>子节点 配置的数据库产品和 databaseId 之间的对应关系,
  25. // 确定最终使用的 databaseId
  26. for (Map.Entry<Object, Object> property : properties.entrySet()) {
  27. if (productName.contains((String) property.getKey())) {
  28. return (String) property.getValue();
  29. }
  30. }
  31. // 没有合适的 databaseId,则返回 null
  32. return null;
  33. }
  34. return productName;
  35. }
  36. // 根据 dataSource 获取 数据库产品名的具体实现
  37. private String getDatabaseProductName(DataSource dataSource) throws SQLException {
  38. Connection con = null;
  39. try {
  40. con = dataSource.getConnection();
  41. DatabaseMetaData metaData = con.getMetaData();
  42. return metaData.getDatabaseProductName();
  43. } finally {
  44. if (con != null) {
  45. try {
  46. con.close();
  47. } catch (SQLException e) {
  48. // ignored
  49. }
  50. }
  51. }
  52. }
  53. }

2.4 解析<mappers>标签

Mybatis 初始化时,除了加载 mybatis-config.xml 文件,还会加载全部的映射配置文件,mybatis-config.xml 文件的 <mapper>节点 会告诉 Mybatis 去哪里查找映射配置文件,及使用了配置注解标识的接口。

  1. /**
  2. * 解析 <mappers>节点,本方法会创建 XMLMapperBuilder对象 加载映射文件,如果映射配置文件存在
  3. * 相应的 Mapper接口,也会加载相应的 Mapper接口,解析其中的注解 并完成向 MapperRegistry 的注册
  4. */
  5. private void mapperElement(XNode parent) throws Exception {
  6. if (parent != null) {
  7. // 处理 <mappers> 的子节点
  8. for (XNode child : parent.getChildren()) {
  9. if ("package".equals(child.getName())) {
  10. // 获取 <package>子节点 中的包名
  11. String mapperPackage = child.getStringAttribute("name");
  12. // 扫描指定的包目录,然后向 MapperRegistry 注册 Mapper接口
  13. configuration.addMappers(mapperPackage);
  14. } else {
  15. // 获取 <mapper>节点 的 resource、url、mapperClass属性,这三个属性互斥,只能有一个不为空
  16. // Mybatis 提供了通过包名、映射文件路径、类全名、URL 四种方式引入映射器。
  17. // 映射器由一个接口和一个 XML配置文件 组成,XML文件 中定义了一个 命名空间namespace,
  18. // 它的值就是接口对应的全路径。
  19. String resource = child.getStringAttribute("resource");
  20. String url = child.getStringAttribute("url");
  21. String mapperClass = child.getStringAttribute("class");
  22. // 如果 <mapper>节点 指定了 resource 或是 url属性,则创建 XMLMapperBuilder对象 解析
  23. // resource 或是 url属性 指定的 Mapper配置文件
  24. if (resource != null && url == null && mapperClass == null) {
  25. ErrorContext.instance().resource(resource);
  26. InputStream inputStream = Resources.getResourceAsStream(resource);
  27. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
  28. mapperParser.parse();
  29. } else if (resource == null && url != null && mapperClass == null) {
  30. ErrorContext.instance().resource(url);
  31. InputStream inputStream = Resources.getUrlAsStream(url);
  32. XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
  33. mapperParser.parse();
  34. } else if (resource == null && url == null && mapperClass != null) {
  35. // 如果 <mapper>节点 指定了 class属性,则向 MapperRegistry 注册 该Mapper接口
  36. Class<?> mapperInterface = Resources.classForName(mapperClass);
  37. configuration.addMapper(mapperInterface);
  38. } else {
  39. throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
  40. }
  41. }
  42. }
  43. }
  44. }

3 XMLMapperBuilder

和 XMLConfigBuilder 一样,XMLMapperBuilder 也继承了 BaseBuilder,其主要负责解析映射配置文件,其解析配置文件的入口方法也是 parse(),另外,XMLMapperBuilder 也将各个节点的解析过程拆分成了一个个小方法,然后由 configurationElement()方法 统一调用。

  1. public class XMLMapperBuilder extends BaseBuilder {
  2. public void parse() {
  3. // 是否已经加载过该配置文件
  4. if (!configuration.isResourceLoaded(resource)) {
  5. // 解析 <mapper>节点
  6. configurationElement(parser.evalNode("/mapper"));
  7. // 将 resource 添加到 configuration 的 loadedResources属性 中,
  8. // 该属性是一个 HashSet<String>类型的集合,其中记录了已经加载过的映射文件
  9. configuration.addLoadedResource(resource);
  10. // 注册 Mapper接口
  11. bindMapperForNamespace();
  12. }
  13. // 处理 configurationElement()方法 中解析失败的 <resultMap>节点
  14. parsePendingResultMaps();
  15. // 处理 configurationElement()方法 中解析失败的 <cacheRef>节点
  16. parsePendingCacheRefs();
  17. // 处理 configurationElement()方法 中解析失败的 <statement>节点
  18. parsePendingStatements();
  19. }
  20. private void configurationElement(XNode context) {
  21. try {
  22. // 获取 <mapper>节点 的 namespace属性
  23. String namespace = context.getStringAttribute("namespace");
  24. if (namespace == null || namespace.equals("")) {
  25. throw new BuilderException("Mapper's namespace cannot be empty");
  26. }
  27. // 使用 MapperBuilderAssistant对象 的 currentNamespace属性 记录 namespace命名空间
  28. builderAssistant.setCurrentNamespace(namespace);
  29. // 解析 <cache-ref>节点,后面的解析方法 也都见名知意
  30. cacheRefElement(context.evalNode("cache-ref"));
  31. cacheElement(context.evalNode("cache"));
  32. parameterMapElement(context.evalNodes("/mapper/parameterMap"));
  33. resultMapElements(context.evalNodes("/mapper/resultMap"));
  34. sqlElement(context.evalNodes("/mapper/sql"));
  35. buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  36. } catch (Exception e) {
  37. throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  38. }
  39. }
  40. }

XMLMapperBuilder 也根据配置文件进行了一系列节点解析,我们着重分析一下比较重要且常见的 <resultMap>节点 和 <sql>节点

3.1 解析<resultMap>节点

select 语句 查询得到的结果是一张二维表,水平方向上是一个个字段,垂直方向上是一条条记录。而 Java 是面向对象的程序设计语言,对象是根据类的定义创建的,类之间的引用关系可以认为是嵌套结构。JDBC 编程 中,为了将结果集中的数据映射成 VO 对象,我们需要自己写代码从结果集中获取数据,然后将数据封装成对应的 VO 对象,并设置好对象之间的关系,这种 ORM 的过程中存在大量重复的代码。

Mybatis 通过 <resultMap>节点 定义了 ORM 规则,可以满足大部分的映射需求,减少重复代码,提高开发效率。

在分析 <resultMap>节点 的解析过程之前,先看一下该过程使用的数据结构。每个 ResultMapping 对象 记录了结果集中的一列与 JavaBean 中一个属性之间的映射关系。<resultMap>节点 下除了 <discriminator>子节点 的其它子节点,都会被解析成对应的 ResultMapping 对象。

  1. public class ResultMapping {
  2. private Configuration configuration;
  3. // 对应节点的 property属性,表示 该列进行映射的属性
  4. private String property;
  5. // 对应节点的 column属性,表示 从数据库中得到的列名或列名的别名
  6. private String column;
  7. // 表示 一个 JavaBean 的完全限定名,或一个类型别名
  8. private Class<?> javaType;
  9. // 进行映射列的 JDBC类型
  10. private JdbcType jdbcType;
  11. // 类型处理器
  12. private TypeHandler<?> typeHandler;
  13. // 该属性通过 id 引用了另一个 <resultMap>节点,它负责将结果集中的一部分列映射成
  14. // 它所关联的结果对象。这样我们就可以通过 join方式 进行关联查询,然后直接映射成
  15. // 多个对象,并同时设置这些对象之间的组合关系(nested嵌套的)
  16. private String nestedResultMapId;
  17. // 该属性通过 id 引用了另一个 <select>节点,它会把指定的列值传入 select属性 指定的
  18. // select语句 中作为参数进行查询。使用该属性可能会导致 ORM 中的 N+1问题,请谨慎使用
  19. private String nestedQueryId;
  20. private Set<String> notNullColumns;
  21. private String columnPrefix;
  22. // 处理后的标志,共有两个:id 和 constructor
  23. private List<ResultFlag> flags;
  24. private List<ResultMapping> composites;
  25. private String resultSet;
  26. private String foreignColumn;
  27. // 是否延迟加载
  28. private boolean lazy;
  29. }

另一个比较重要的类是 ResultMap,每个 <resultMap>节点 都会被解析成一个 ResultMap 对象,其中每个节点所定义的映射关系,则使用 ResultMapping 对象 表示。

  1. public class ResultMap {
  2. private Configuration configuration;
  3. // 这些属性一一对应了 <resultMap> 中的属性
  4. private String id;
  5. private Class<?> type;
  6. // 记录了除 <discriminator>节点 之外的其它映射关系(即,ResultMapping对象集合)
  7. private List<ResultMapping> resultMappings;
  8. // 记录了映射关系中带有 ID标志 的映射关系,如:<id>节点 和 <constructor>节点 的 <idArg>子节点
  9. private List<ResultMapping> idResultMappings;
  10. // 记录了映射关系中带有 Constructor标志 的映射关系,如:<constructor>所有子元素
  11. private List<ResultMapping> constructorResultMappings;
  12. // 记录了映射关系中不带有 Constructor标志 的映射关系
  13. private List<ResultMapping> propertyResultMappings;
  14. // 记录了所有映射关系中涉及的 column属性 的集合
  15. private Set<String> mappedColumns;
  16. // 记录了所有映射关系中涉及的 property属性 的集合
  17. private Set<String> mappedProperties;
  18. // 鉴别器,对应 <discriminator>节点
  19. private Discriminator discriminator;
  20. // 是否含有嵌套的结果映射,如果某个映射关系中存在 resultMap属性,
  21. // 且不存在 resultSet属性,则为true
  22. private boolean hasNestedResultMaps;
  23. // 是否含有嵌套查询,如果某个属性映射存在 select属性,则为true
  24. private boolean hasNestedQueries;
  25. // 是否开启自动映射
  26. private Boolean autoMapping;
  27. }

了解了 ResultMapping 和 ResultMap 记录的信息之后,下面开始介绍 <resultMap>节点 的解析过程。在 XMLMapperBuilder 中通过 resultMapElements()方法 解析映射配置文件中的全部 <resultMap>节点,该方法会循环调用 resultMapElement()方法 处理每个 <resultMap> 节点。

  1. private ResultMap resultMapElement(XNode resultMapNode) throws Exception {
  2. return resultMapElement(resultMapNode, Collections.<ResultMapping> emptyList());
  3. }
  4. private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {
  5. ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
  6. // <resultMap> 的 id属性,默认值会拼装所有父节点的 id 或 value 或 property属性值
  7. String id = resultMapNode.getStringAttribute("id",
  8. resultMapNode.getValueBasedIdentifier());
  9. // <resultMap> 的 type属性,表示结果集将被映射成 type 指定类型的对象
  10. String type = resultMapNode.getStringAttribute("type",
  11. resultMapNode.getStringAttribute("ofType",
  12. resultMapNode.getStringAttribute("resultType",
  13. resultMapNode.getStringAttribute("javaType"))));
  14. // 该属性指定了该 <resultMap>节点 的继承关系
  15. String extend = resultMapNode.getStringAttribute("extends");
  16. // 为 true 则启动自动映射功能,该功能会自动查找与列明相同的属性名,并调用 setter方法,
  17. // 为 false,则需要在 <resultMap>节点 内注明映射关系才会调用对应的 setter方法
  18. Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
  19. // 解析 type类型
  20. Class<?> typeClass = resolveClass(type);
  21. Discriminator discriminator = null;
  22. // 该集合用来记录解析结果
  23. List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
  24. resultMappings.addAll(additionalResultMappings);
  25. // 获取并处理 <resultMap> 的子节点
  26. List<XNode> resultChildren = resultMapNode.getChildren();
  27. // child 单数形式,children 复数形式
  28. for (XNode resultChild : resultChildren) {
  29. // 处理 <constructor>节点
  30. if ("constructor".equals(resultChild.getName())) {
  31. processConstructorElement(resultChild, typeClass, resultMappings);
  32. // 处理 <discriminator>节点
  33. } else if ("discriminator".equals(resultChild.getName())) {
  34. discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
  35. } else {
  36. // 处理 <id>, <result>, <association>, <collection> 等节点
  37. List<ResultFlag> flags = new ArrayList<ResultFlag>();
  38. if ("id".equals(resultChild.getName())) {
  39. flags.add(ResultFlag.ID);
  40. }
  41. // 创建 ResultMapping对象,并添加到 resultMappings集合
  42. resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
  43. }
  44. }
  45. ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
  46. try {
  47. return resultMapResolver.resolve();
  48. } catch (IncompleteElementException e) {
  49. configuration.addIncompleteResultMap(resultMapResolver);
  50. throw e;
  51. }
  52. }

从上面的代码我们可以看到,Mybatis 从 <resultMap>节点 获取到 id 属性 和 type 属性值 之后,就会通过 XMLMapperBuilder 的 buildResultMappingFromContext()方法 为 <result>节点 创建对应的 ResultMapping 对象。

  1. /**
  2. * 根据上下文环境构建 ResultMapping
  3. */
  4. private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) throws Exception {
  5. // 获取各个节点的属性,见文知意
  6. String property;
  7. if (flags.contains(ResultFlag.CONSTRUCTOR)) {
  8. property = context.getStringAttribute("name");
  9. } else {
  10. property = context.getStringAttribute("property");
  11. }
  12. String column = context.getStringAttribute("column");
  13. String javaType = context.getStringAttribute("javaType");
  14. String jdbcType = context.getStringAttribute("jdbcType");
  15. String nestedSelect = context.getStringAttribute("select");
  16. String nestedResultMap = context.getStringAttribute("resultMap",
  17. processNestedResultMappings(context, Collections.<ResultMapping> emptyList()));
  18. String notNullColumn = context.getStringAttribute("notNullColumn");
  19. String columnPrefix = context.getStringAttribute("columnPrefix");
  20. String typeHandler = context.getStringAttribute("typeHandler");
  21. String resultSet = context.getStringAttribute("resultSet");
  22. String foreignColumn = context.getStringAttribute("foreignColumn");
  23. boolean lazy = "lazy".equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
  24. Class<?> javaTypeClass = resolveClass(javaType);
  25. @SuppressWarnings("unchecked")
  26. Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
  27. JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  28. // 创建 ResultMapping对象 并返回
  29. return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
  30. }

得到 ResultMapping 对象集合 之后,会调用 ResultMapResolver 的 resolve()方法,该方法会调用 MapperBuilderAssistant 的 addResultMap()方法 创建 ResultMap 对象,并将 ResultMap 对象 添加到 Configuration 的 resultMaps 集合 中保存。

  1. public class MapperBuilderAssistant extends BaseBuilder {
  2. public ResultMap addResultMap(String id, Class<?> type, String extend,
  3. Discriminator discriminator, List<ResultMapping> resultMappings, Boolean autoMapping) {
  4. // ResultMap 的 完整id 是 "namespace.id" 的格式
  5. id = applyCurrentNamespace(id, false);
  6. // 获取 父ResultMap 的 完整id
  7. extend = applyCurrentNamespace(extend, true);
  8. // 针对 extend属性 进行的处理
  9. if (extend != null) {
  10. if (!configuration.hasResultMap(extend)) {
  11. throw new IncompleteElementException("Could not find a parent resultmap with id '" + extend + "'");
  12. }
  13. // 父ResultMap对象
  14. ResultMap resultMap = configuration.getResultMap(extend);
  15. // 父ResultMap对象 的 ResultMapping集合
  16. List<ResultMapping> extendedResultMappings = new ArrayList<ResultMapping>(resultMap.getResultMappings());
  17. // 删除需要覆盖的 ResultMapping集合
  18. extendedResultMappings.removeAll(resultMappings);
  19. // Remove parent constructor if this resultMap declares a constructor.
  20. boolean declaresConstructor = false;
  21. for (ResultMapping resultMapping : resultMappings) {
  22. if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
  23. declaresConstructor = true;
  24. break;
  25. }
  26. }
  27. if (declaresConstructor) {
  28. Iterator<ResultMapping> extendedResultMappingsIter = extendedResultMappings.iterator();
  29. while (extendedResultMappingsIter.hasNext()) {
  30. if (extendedResultMappingsIter.next().getFlags().contains(ResultFlag.CONSTRUCTOR)) {
  31. extendedResultMappingsIter.remove();
  32. }
  33. }
  34. }
  35. // 添加需要被继承下来的 ResultMapping集合
  36. resultMappings.addAll(extendedResultMappings);
  37. }
  38. ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
  39. .discriminator(discriminator)
  40. .build();
  41. configuration.addResultMap(resultMap);
  42. return resultMap;
  43. }
  44. }

3.2 解析<sql>节点

在映射配置文件中,可以使用 <sql>节点 定义可重用的 SQL 语句片段,当需要重用 <sql>节点 中定义的 SQL 语句片段 时,只需要使用 <include>节点 引入相应的片段即可,这样,在编写 SQL 语句 以及维护这些 SQL 语句 时,都会比较方便。XMLMapperBuilder 的 sqlElement()方法 负责解析映射配置文件中定义的 全部<sql>节点。

  1. private void sqlElement(List<XNode> list) throws Exception {
  2. if (configuration.getDatabaseId() != null) {
  3. sqlElement(list, configuration.getDatabaseId());
  4. }
  5. sqlElement(list, null);
  6. }
  7. private void sqlElement(List<XNode> list, String requiredDatabaseId) throws Exception {
  8. // 遍历 <sql>节点
  9. for (XNode context : list) {
  10. String databaseId = context.getStringAttribute("databaseId");
  11. String id = context.getStringAttribute("id");
  12. // 为 id 添加命名空间
  13. id = builderAssistant.applyCurrentNamespace(id, false);
  14. // 检测 <sql> 的 databaseId 与当前 Configuration 中记录的 databaseId 是否一致
  15. if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
  16. // 记录到 sqlFragments(Map<String, XNode>) 中保存
  17. sqlFragments.put(id, context);
  18. }
  19. }
  20. }

4 XMLStatementBuilder

5 绑定 Mapper 接口

通过之前对 binding 模块 的解析可知,每个映射配置文件的命名空间可以绑定一个 Mapper 接口,并注册到 MapperRegistry 中。XMLMapperBuilder 的 bindMapperForNamespace()方法 中,完成了映射配置文件与对应 Mapper 接口 的绑定。

  1. public class XMLMapperBuilder extends BaseBuilder {
  2. private void bindMapperForNamespace() {
  3. // 获取映射配置文件的命名空间
  4. String namespace = builderAssistant.getCurrentNamespace();
  5. if (namespace != null) {
  6. Class<?> boundType = null;
  7. try {
  8. // 解析命名空间对应的类型
  9. boundType = Resources.classForName(namespace);
  10. } catch (ClassNotFoundException e) {
  11. //ignore, bound type is not required
  12. }
  13. if (boundType != null) {
  14. // 是否已加载 boundType接口
  15. if (!configuration.hasMapper(boundType)) {
  16. // 追加个 "namespace:" 的前缀,并添加到 Configuration 的 loadedResources集合 中
  17. configuration.addLoadedResource("namespace:" + namespace);
  18. // 添加到 Configuration的mapperRegistry集合 中,另外,往这个方法栈的更深处看 会发现
  19. // 其创建了 MapperAnnotationBuilder对象,并调用了该对象的 parse()方法 解析 Mapper接口
  20. configuration.addMapper(boundType);
  21. }
  22. }
  23. }
  24. }
  25. }
  26. public class MapperRegistry {
  27. public <T> void addMapper(Class<T> type) {
  28. if (type.isInterface()) {
  29. if (hasMapper(type)) {
  30. throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
  31. }
  32. boolean loadCompleted = false;
  33. try {
  34. knownMappers.put(type, new MapperProxyFactory<T>(type));
  35. // 解析 Mapper接口 type 中的信息
  36. MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
  37. parser.parse();
  38. loadCompleted = true;
  39. } finally {
  40. if (!loadCompleted) {
  41. knownMappers.remove(type);
  42. }
  43. }
  44. }
  45. }
  46. }
  47. public class MapperAnnotationBuilder {
  48. public void parse() {
  49. String resource = type.toString();
  50. // 是否已经加载过该接口
  51. if (!configuration.isResourceLoaded(resource)) {
  52. // 检查是否加载过该接口对应的映射文件,如果未加载,则创建 XMLMapperBuilder对象
  53. // 解析对应的映射文件,该过程就是前面介绍的映射配置文件解析过程
  54. loadXmlResource();
  55. configuration.addLoadedResource(resource);
  56. assistant.setCurrentNamespace(type.getName());
  57. // 解析 @CacheNamespace注解
  58. parseCache();
  59. // 解析 @CacheNamespaceRef注解
  60. parseCacheRef();
  61. // type接口 的所有方法
  62. Method[] methods = type.getMethods();
  63. for (Method method : methods) {
  64. try {
  65. if (!method.isBridge()) {
  66. // 解析 SelectKey、ResultMap 等注解,并创建 MappedStatement对象
  67. parseStatement(method);
  68. }
  69. } catch (IncompleteElementException e) {
  70. // 如果解析过程出现 IncompleteElementException异常,可能是因为引用了
  71. // 未解析的注解,这里将出现异常的方法记录下来,后面提供补偿机制,重新进行解析
  72. configuration.addIncompleteMethod(new MethodResolver(this, method));
  73. }
  74. }
  75. }
  76. // 遍历 configuration 中的 incompleteMethods集合,集合中记录了未解析的方法
  77. // 重新调用这些方法进行解析
  78. parsePendingMethods();
  79. }
  80. }

另外,在 MapperAnnotationBuilder 的 parse()方法 中解析的注解,都能在映射配置文件中找到与之对应的 XML 节点,且两者的解析过程也非常相似。