mybatis原理解析---配置文件读取及SqlSessionFactory构建

mybatis的运行分为两个部分,第一个部分是读取配置文件并缓存到Configuration对象,用以创建SqlSessionFactory对象。第二部分是sqlSession运行过程。这篇文章主要讨论如何解析配置文件得到Configuration对象,以及Configuration对象中一些重要属性的含义。

1.配置文件解析

先来看读取配置文件得到Configuration对象的过程。mybatis的运行入口是SqlSessionFactoryBuilder.build()方法,通过给这个方法传入一个配置文件的输入流,则可以拿到SqlSessionFactory对象。SqlSessionFactory对象代表的是一个数据库对象,通过它可以获得与数据库会话的sqlSession对象。所以将配置文件解析为Configuration对象是在SqlSessionFactoryBuilder.build()方法里实现的。这里解析的配置文件包括mybatis-config.xml和各个mapper.xml文件,下面是build()方法的源码:

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      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来实现的,这个类中是包含一个Configuration对象的,并且限制了一个XMLConfigBuilder对象只能解析一次得到一个Configuration对象,下面具体看下其parse()方法:

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

这里负责拿出根节点,然后里面具体元素的解析是交给了parseConfiguration()方法,下面是其源码:

private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      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"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQ
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值