一、SqlSessionFactory 对象初始化

 //加载全局配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//1.获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

MyBatis 3源码解析(一)-LMLPHP

1.调用SqlSessionFactoryBuilder的build(inputStream);方法,方法如下:

public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }

实际上调用如下方法;

  public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //XMLConfigBuilder是对mybatis的配置文件进行解析的类
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //1.调用当前类的parse() 方法,返回configuration。2.调用build方法,返回SqlSessionFactory
      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.
      }
    }
  }
  • 首先传入全局配置文件的输入流,创建了XMLConfigBuilder对象。然后调用XMLConfigBuilder 的parse()方法。代码如下:
  public Configuration parse() {
    //判断Configuration是否解析过,Configuration是全局变量,只需要解析创建一次即可
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    //调用下面的方法,parser.evalNode("/configuration")解析XML配置的configuration节点的内容,得到XNode对象
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

parser.evalNode(“/configuration”)是调用了XPathParser类的evalNode方法返回的是XNode对象。XNode对象保存了解析后的对应节点下的所有信息。

  • 然后parseConfiguration(parser.evalNode("/configuration")); 方法,代码如下:
 //根据root中存储的是configuration节点的内容
 private void parseConfiguration(XNode root) {
    try {
       //设置settings配置
      Properties settings = settingsAsPropertiess(root.evalNode("settings"));
       //设置properties配置
      propertiesElement(root.evalNode("properties"));
      loadCustomVfs(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));

      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      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);
    }
  }

可以看出parse的作用是解析mybatis-config.xml的configuration节点的内容,然后挨个赋值给configuration对象的属性;

  • settingsElement(settings); 方法如下:将全局配置文件中所有结点的配置信息都设置到了configuration对象中
private void settingsElement(Properties props) throws Exception {
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
  • mapperElement(root.evalNode("mappers")); 方法,则是将是对SQL映射文件进行了解析。解析后将信息设置到了configuration对象中
  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.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();

解析mapper映射文件代码如下:

 private void configurationElement(XNode context) {
    try {
      String namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.equals("")) {
        throw new BuilderException("Mapper's namespace cannot be empty");
      }
      builderAssistant.setCurrentNamespace(namespace);
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      sqlElement(context.evalNodes("/mapper/sql"));
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
    }
  }

到这里 return build(parser.parse()); 就要返回了,build方法如下:

  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

返回的SqlSessionFactory 对象中封装了所有的配置信息。Configuration封装了所有配置文件的详细信息。

总结:把配置文件的信息解析并保存在Configuration对象中,返回包含了Configuration的DefaultSqlSession对象。

04-09 21:23