zoukankan      html  css  js  c++  java
  • Spring mybatis源码篇章-Mybatis主文件加载

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-SqlSessionFactory

    前话

    本文承接前文的内容继续往下扩展,通过Spring与Mybatis的整合也一步步去了解Mybatis的工作机制。

    使用Mybatis,有多种加载方式,本文只罗列主文件加载方式

    加载指定的mybatis主文件

    1.Mybatis模板文件,其中的属性含义可查看官网中文版链接

    <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties />
        <settings />
        <typeAliases />
        <typeHandlers />
        <objectFactory />
        <plugins />
        <environments>
            <environment>
                <transactionManager />
                <dataSource />
            </environment>
        </environments>
        <databaseIdProvider />
        <mappers />
    </configuration>
    

    2.针对上述的主文件加载,Spring如果配置了SqlSessionFactoryBean的属性configLocation将会执行下述代码进行解析

    //主要加载指定路径的mybatis主配置文件,尚未解析
    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configLocation != null) {
          xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
          configuration = xmlConfigBuilder.getConfiguration();
        }
     ...
     ...
     //对主配置文件进行解析
     if (xmlConfigBuilder != null) {
          try {
            xmlConfigBuilder.parse();
    
            if (this.logger.isDebugEnabled()) {
              this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
            }
          } catch (Exception ex) {
            throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
          } finally {
            ErrorContext.instance().reset();
          }
        }
    

    解析主文件的相关配置

    我们直接观察XmlConfigBuilder#parse()这个入口方法

    public Configuration parse() {
        if (parsed) {
          throw new BuilderException("Each XMLConfigBuilder can only be used once.");
        }
        parsed = true;
        //此句为关键,从configuration标志处开始解析,所以主文件必须具备configuration根节点,不然会报错
        parseConfiguration(parser.evalNode("/configuration"));
        return configuration;
      }
    

    直接分析parseConfiguration()方法(主要解析主文件的相关节点属性)

      private void parseConfiguration(XNode root) {
        try {
          propertiesElement(root.evalNode("properties")); //issue #117 read properties first
          typeAliasesElement(root.evalNode("typeAliases"));
          pluginElement(root.evalNode("plugins"));
          objectFactoryElement(root.evalNode("objectFactory"));
          objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
          settingsElement(root.evalNode("settings"));
          environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631
          databaseIdProviderElement(root.evalNode("databaseIdProvider"));
          typeHandlerElement(root.evalNode("typeHandlers"));
          mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
          throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
      }
    

    也就是针对前文提及的模板文件的节点进行分别的解析,这样就比较清晰了

    mapper节点

    笔者此处只关注对mapper节点属性的解析,直接查看XMLConfigBuilder#mapperElement()方法,源码如下

    private void mapperElement(XNode parent) throw Exception{
    	if (parent != null) {
    	  //对configuration下的<mappers>集合进行遍历,其下有mapper和package标签节点
          for (XNode child : parent.getChildren()) {
            //package节点,即扫描指定包及其子包下的所有class类并保存至Map集合中
            if ("package".equals(child.getName())) {
              String mapperPackage = child.getStringAttribute("name");
              configuration.addMappers(mapperPackage);
            } else {
              String resource = child.getStringAttribute("resource");
              String url = child.getStringAttribute("url");
              String mapperClass = child.getStringAttribute("class");
              //mapper标签指定resource属性表明是从classpath环境中加载指定的xml文件
              if (resource != null && url == null && mapperClass == null) {
                ErrorContext.instance().resource(resource);
                InputStream inputStream = Resources.getResourceAsStream(resource);
                //这里的XMLMapperBuilder类是对Mapper的XML文件进行解析,具体解析我们放置下一章节讲
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                mapperParser.parse();
              } else if (resource == null && url != null && mapperClass == null) {
    			//加载url模式的XML文件,支持"file:///"
                ErrorContext.instance().resource(url);
                InputStream inputStream = Resources.getUrlAsStream(url);
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                mapperParser.parse();
              } else if (resource == null && url == null && mapperClass != null) {
    			//加载的是指定的Class文件,配置的类为接口类,此点须注意
                Class<?> mapperInterface = Resources.classForName(mapperClass);
                configuration.addMapper(mapperInterface);
              } else {
    			//这里指出单个Mapper标签中url、resource、class属性只能选择其一
                throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
              }
            }
          }
        }
    }
    

    上述应用最广泛的为package节点和mapper节点配置,例如

    <mappers>
    	<mapper resource=""></mapper>
    	<package name=""></package>
    </mappers>
    

    不管是使用哪一种方式,均会走入这个MapperRegistry#addMapper()方法

    public <T> void addMapper(Class<T> type){
    	//这里指出MapperClass类必须是个接口类,否则不会被添加
    	if (type.isInterface()) {
          if (hasMapper(type)) {
            throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
          }
          boolean loadCompleted = false;
          try {
            //放入Map集合中,并对指定的mapper接口类进行代理的包装
            knownMappers.put(type, new MapperProxyFactory<T>(type));
            // It's important that the type is added before the parser is run
            // otherwise the binding may automatically be attempted by the
            // mapper parser. If the type is already known, it won't try.
            //这里就是关键处理类了,对可能存在注解的MapperInterface接口进行处理
            MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
            parser.parse();
            loadCompleted = true;
          } finally {
            if (!loadCompleted) {
              knownMappers.remove(type);
            }
          }
        }
    }
    

    上述代码大意就是对mapper节点指定的class或者是package节点指定的包下的class,都会被包装成MapperAnnotationBuilder类,此类主要使用反射的思想去解析对应的class(dao接口),我们继续往下看


    那么肯定会有疑问,如果我mapper指定的是xml文件资源呢,例如

    <mapper resource="classpath:mappers/user.xml"></mapper>
    

    那其实并不会去关联相应的dao接口,这个就需要和Spring另外提供的MapperScannerConfigurer来搭配使用了。这个我们后文再分析

    MapperAnnotationBuilder

    首先观察下MapperAnnotationBuilder类的构造方法看看,注意type参数代表MapperInterface接口类,也就是DAO接口

    public MapperAnnotationBuilder(Configuration configuration, Class<?> type) {
        String resource = type.getName().replace('.', '/') + ".java (best guess)";
        this.assistant = new MapperBuilderAssistant(configuration, resource);
        this.configuration = configuration;
        this.type = type;
        //从这里看出我们熟悉的CRUD注解了,它这里先预存到sqlAnnotationTypes集合中
        sqlAnnotationTypes.add(Select.class);
        sqlAnnotationTypes.add(Insert.class);
        sqlAnnotationTypes.add(Update.class);
        sqlAnnotationTypes.add(Delete.class);
    
        sqlProviderAnnotationTypes.add(SelectProvider.class);
        sqlProviderAnnotationTypes.add(InsertProvider.class);
        sqlProviderAnnotationTypes.add(UpdateProvider.class);
        sqlProviderAnnotationTypes.add(DeleteProvider.class);
      }
    

    再而着重关注下其解析方法MapperAnnotationBuilder#parse()方法

    public void parse() {
    	 //获取接口类的名字,比如com.jing.test.TestMapper的输出为class com.jing.test.TestMapper
        String resource = type.toString();
        if (!configuration.isResourceLoaded(resource)) {
          //加载xml文件,这里可以看出是通过Class文件去寻找XML文件
          loadXmlResource();
          configuration.addLoadedResource(resource);
          //工作空间为当前类全名
          assistant.setCurrentNamespace(type.getName());
          parseCache();
          parseCacheRef();
          //获得class类中的方法
          Method[] methods = type.getMethods();
          for (Method method : methods) {
            try {
              //解析方法上的注解式sql语句
              parseStatement(method);
            } catch (IncompleteElementException e) {
              configuration.addIncompleteMethod(new MethodResolver(this, method));
            }
          }
        }
        parsePendingMethods();
      }
    

    着重关注几个方法

    loadXmlResource()

    其通过class类去找寻对应的XML配置

    	// Spring may not know the real resource name so we check a flag
        // to prevent loading again a resource twice
        // this flag is set at XMLMapperBuilder#bindMapperForNamespace
        if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
          //这里发现它会去加载跟Class文件同一目录下且同名的xml配置文件
          String xmlResource = type.getName().replace('.', '/') + ".xml";
          InputStream inputStream = null;
          try {
            inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
          } catch (IOException e) {
            // ignore, resource is not required
            //这里发现找不到相应的xml配置文件也没关系,这里其实它认为有其他两种方式实现
            //1.SqlsessionFactory指定了mapperLocations
            //2.Class类上有注解形式代替了xml配置
          }
          if (inputStream != null) {
            //解析相应的mapper xml
            XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
            xmlParser.parse();
          }
        }
    

    根据上述的代码得知,优先判断当前类下有无XML配置,有通过XmlMapperBuilder去解析,但这不是必须的~因为Mybatis也支持通过注解方式去解析

    parseStatement()

    注解方式解析生成MappedStatement

    void parseStatement(Method method) {
        //获得为ParamMap,ibatis内部实现了HashMap
        Class<?> parameterTypeClass = getParameterType(method);
        //脚本驱动器
        LanguageDriver languageDriver = getLanguageDriver(method);
        //寻找方法名头上是否含有@Select/@Update/@Delete/@Insert注解,没有则返回null
        SqlSource sqlSource = getSqlSourceFromAnnotations(method, parameterTypeClass, languageDriver);
        if (sqlSource != null) {
          //查看方法头有无@Option注解
          Options options = method.getAnnotation(Options.class);
          //注解方式的mapperStatementId为 ${Class全名}.${方法名}
          final String mappedStatementId = type.getName() + "." + method.getName();
          Integer fetchSize = null;
          Integer timeout = null;
          //默认使用预处理方式
          StatementType statementType = StatementType.PREPARED;
          ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
          //获取方法的@Select/@Update之类的SQL执行类型
          SqlCommandType sqlCommandType = getSqlCommandType(method);
          boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
          boolean flushCache = !isSelect;
          boolean useCache = isSelect;
    
          ****
          ****
    
          String resultMapId = null;
          //读取返回类型@ResultMap注解,形式为@ResultMap(value="modelMap"),则必须存在class文件对应的sql XML配置文件,其中的value是sql xml配置中的<resultMap id="modelMap" />
          ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
          //如果存在@ResultMap注解,则使用其中的value作为返回集合id
          if (resultMapAnnotation != null) {
            String[] resultMaps = resultMapAnnotation.value();
            StringBuilder sb = new StringBuilder();
            for (String resultMap : resultMaps) {
              if (sb.length() > 0) {
                sb.append(",");
              }
              sb.append(resultMap);
            }
            resultMapId = sb.toString();
          } else if (isSelect) {
            //如果是查询式注解则采用另外方式生成,最后格式为${class类全名}.${methodName}-${-methodParameterType1-methodParamterType2-...}
            resultMapId = parseResultMap(method);
          }
    	  //最终生成MappedStatement执行对象
          assistant.addMappedStatement(
              mappedStatementId,
              sqlSource,
              statementType,
              sqlCommandType,
              fetchSize,
              timeout,
              // ParameterMapID
              null,
              parameterTypeClass,
              resultMapId,
              getReturnType(method),
              resultSetType,
              flushCache,
              useCache,
              // TODO gcode issue #577
              false,
              keyGenerator,
              keyProperty,
              keyColumn,
              // DatabaseID
              null,
              languageDriver,
              // ResultSets
              options != null ? nullOrEmpty(options.resultSets()) : null);
        }
      }
    

    上述的代码很冗长,不作具体讲解,不过其表露了如果相应的接口dao类定义了类似@Select/@Delete的注解方式,其会覆盖XML方式加载的同idMappedStatement

    不过不推荐使用在类上使用注解方式来生成MappedStatement,因为维护性很差。

    总结

    本文主要讲的是mybatis主文件加载生成MappedStatement方式,并对其中主要的mapper节点解析作简单的分析,可以归总如下

    1.mapper节点中resourceurlclass的属性使用,只能择其一

    2.如果使用了package节点以及mapper节点指定使用了class或者url属性的话,便会通过DAO接口类方式来生成MappedStatement对象。并且如果接口类实现了类似@Select等注解,则会默认覆盖对应XML文件指定的同ID的MappedStatement

    3.一般在使用主文件时,如果用户想偷懒,就使用mappers节点下的mapper节点或者package节点来指定加载DAO接口类即可。但不推荐在DAO接口类上使用注解,不利于维护

    4.如果使用第三点提及的加载方式,则必须确保每个XML文件与对应的DAO接口在同一个目录下。当然用户想将接口与XML文件分别管理,则需要使用相应的MapperScannerConfigurer类了~~

    5.Mybatis工作比较核心的元素是MappedStatement对象,后文会提及很多次,这也是我们必须时常关注的类~~~

    6.官方以及笔者推荐一个DAO接口类对应一个XML文件,前者定义数据库CRUD方式,后者维护相应的SQL

  • 相关阅读:
    hibernate常用查询语句动态生成类(包括条件和无条件查询)
    Eclipse常用插件更新下载地址列表
    IT相关网站列表
    /etc/目录下的passwd文件内容详解
    关于jfreechart创建web报表图片的流程初解
    博客地址列表
    java编码转换的详细过程 (转)
    偿债
    汽车变速器(自动挡)英文缩写
    Firefox 快捷键列表
  • 原文地址:https://www.cnblogs.com/question-sky/p/6606507.html
Copyright © 2011-2022 走看看