MyBatis的初始化过程实现原理概述

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lichunericli/article/details/82557565

MyBatis的初始化的过程其实就是解析配置文件和初始化Configuration的过程。

1.MyBatis的通用执行流程
参照GOF提出的23种设计模式,可以看出MyBatis的执行流程算是种通用的模板模式,其实现过程也简单:
首先通过相关的资源文件配置的加载得到对应的InputStream;
然后通过SqlSessionFactoryBuilder的build(InputStream)方法来构建SqlSessionFactory;
接着通过SqlSessionFactory的openSession方法来得到SqlSession;
接下来通过SqlSession来执行对应SQL语句实现;
最后封装底层JDBC返回的执行结果,然后返回到业务端使用。

2.SqlSessionFactory的构建
MyBatis对资源的加载是通过Resources类来处理的,通过Resources类可以得到文件的Properties,InputStream和Reader等。究其底层实现原理,都是通过urlString或者resourceString来得到对应的URL,然后通过URL来获取对应的InputStream,最后进行封装返回结果。

SqlSessionFactory的创建比较简单,其实现源码如下所示:
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
   XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
   return build(parser.parse()); // 此处构建返回的是DefaultSqlSessionFactory
}

3.Configuration的初始化
Configuration的初始化是通过XMLConfigBuilder的parse来实现的,
public Configuration parse() {
   // 通过XPathParser来解析,将XML中数据封装成XNode,便于后续解析
   parseConfiguration(parser.evalNode("/configuration"));
   return configuration;
}

private void parseConfiguration(XNode root) {
   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);
   environmentsElement(root.evalNode("environments"));
   databaseIdProviderElement(root.evalNode("databaseIdProvider"));
   typeHandlerElement(root.evalNode("typeHandlers"));
   mapperElement(root.evalNode("mappers"));

在生成对象XMLConfigBuilder时会进行Configuration的初始化,在Configuration的初始化中会看到进行TypeAliasRegistry和LanguageDriverRegistry的注册实现。在依次解析配置中的节点内容时会进丰富Configuration的参数,例如在解析environments节点内容时会根据transactionManager的配置来创建事务管理器,以及根据dataSource的配置来创建DataSource对象。

总结:关于XML文件本身是通过XPath和Dom4来解析的,对于其中XML内容的解析则是通过PropertyParser,GenericTokenParser和TokenHandler来实现的。PropertyParser用来替换掉#{}和${}相关格式的字符串,GenericTokenParser和TokenHandler用来处理相关的参数。在Map中查不到对应的key【XML中的id】时,或者重复添加映射时【xml中的id重复】时,或者绑定的Mapper中某个方法出错时会抛出此BindingException异常。

猜你喜欢

转载自blog.csdn.net/lichunericli/article/details/82557565
今日推荐