inputstream 初始化_Mybatis 源码解析(一)—— 初始化过程

前言

什么是 MyBatis?

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

关于mybatis的基本使用,可以参考mybatis中文官网

https://mybatis.org/mybatis-3/zh/index.html

1. 基本使用

public static void main(String[] args) throws Exception {  String mybatisConfigXmlPath = "mybatisConfig.xml";  InputStream inputStream = Resources.getResourceAsStream(mybatisConfigXmlPath);  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  SqlSession sqlSession = sqlSessionFactory.openSession();  try {      TestMapper testMapper = sqlSession.getMapper(TestMapper.class);      List list = testMapper.listObject();  } finally {      sqlSession.close();  }}

2. 初始化过程

总体上初始化分为以下步骤

  1. 获取配置文件

  2. 创建 SqlSessionFactory

其中创建 SqlSessionFactory 就是初始化过程的精髓

2.1 SqlSessionFactory创建过程

下面来看看 SqlSessionFactoryBuilder 的部分源码

public class SqlSessionFactoryBuilder { public SqlSessionFactory build(Reader reader) {   return build(reader, null, null);} public SqlSessionFactory build(Reader reader, String environment, Properties properties) {   try {     XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);     return build(parser.parse());  } catch (Exception e) {     throw ExceptionFactory.wrapException("Error building SqlSession.", e);  } finally {     ErrorContext.instance().reset();     try {       reader.close();    } catch (IOException e) {       // Intentionally ignore. Prefer previous error.    }  }} public SqlSessionFactory build(InputStream inputStream) {   return build(inputStream, null, null);} 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.    }  }} public SqlSessionFactory build(Configuration config) {   return new DefaultSqlSessionFactory(config);}}

Builder的过程为

  1. 根据配置文件的输入(InputStream/Reader)创建 XMLConfigBuilder

  2. 通过 XMLConfigBuilder 解析配置文件得到 Configuration

  3. 通过 Configuration 创建出 DefaultSqlSessionFactory

2.2 XMLConfigBuilder 初始化过程

XML的各种解析类

789a7f92da280ad53474ec6c26bca0c2.png

  1. XMLConfigBuilder:解析配置文件

  2. XMLMapperBuilder:解析mapper文件

  3. XMLStatementBuilder:解析statement语句

下面来看看 XMLConfigBuilder 的部分源码

public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {  this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);} private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {super(new Configuration());ErrorContext.instance().resource("SQL Mapper Configuration");this.configuration.setVariables(props);this.parsed = false;this.environment = environment;this.parser = parser;}// 解析过程入口public Configuration parse() {if (parsed) {  throw new BuilderException("Each XMLConfigBuilder can only be used once.");}parsed = true;parseConfiguration(parser.evalNode("/configuration"));return configuration;}// 从 xml 文件的 configuration 节点开始解析private void parseConfiguration(XNode root) {try {// 根据 config 文件的各个属性进行解析  propertiesElement(root.evalNode("properties"));  Properties settings = settingsAsProperties(root.evalNode("settings"));  loadCustomVfs(settings);  loadCustomLogImpl(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 SQL Mapper Configuration. Cause: " + e, e);}}

总体来说,就是需要解析配置文件中的以下属性(来自官网)

b33a4e943d4671ba0619e487adacf6ae.png

以下属性解析比较类似,主要是获取属性,存在 XMLConfigBuilder 的 configuration 中,例如

private void propertiesElement(XNode context) throws Exception {if (context != null) {  Properties defaults = context.getChildrenAsProperties();  String resource = context.getStringAttribute("resource");  String url = context.getStringAttribute("url");  if (resource != null && url != null) {    throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other.");  }  if (resource != null) {    defaults.putAll(Resources.getResourceAsProperties(resource));  } else if (url != null) {    defaults.putAll(Resources.getUrlAsProperties(url));  }  Properties vars = configuration.getVariables();  if (vars != null) {    defaults.putAll(vars);  }  parser.setVariables(defaults);  // 保存在 configuration 中  configuration.setVariables(defaults);}}
  • properties

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置

<properties resource="org/mybatis/example/config.properties">  <property name="username" value="dev_user"/>  <property name="password" value="F2Fa3!33TYyg"/>properties>
  • settings

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

<settings><setting name="cacheEnabled" value="true"/><setting name="lazyLoadingEnabled" value="true"/><setting name="multipleResultSetsEnabled" value="true"/><setting name="useColumnLabel" value="true"/><setting name="useGeneratedKeys" value="false"/><setting name="autoMappingBehavior" value="PARTIAL"/><setting name="autoMappingUnknownColumnBehavior" value="WARNING"/><setting name="defaultExecutorType" value="SIMPLE"/><setting name="defaultStatementTimeout" value="25"/><setting name="defaultFetchSize" value="100"/><setting name="safeRowBoundsEnabled" value="false"/><setting name="mapUnderscoreToCamelCase" value="false"/><setting name="localCacheScope" value="SESSION"/><setting name="jdbcTypeForNull" value="OTHER"/><setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>settings>
  • objectFactory

每次 MyBatis 创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成实例化工作。默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认无参构造方法,要么通过存在的参数映射来调用带有参数的构造方法。如果想覆盖对象工厂的默认行为,可以通过创建自己的对象工厂来实现。

<objectFactory type="org.mybatis.example.ExampleObjectFactory"><property name="someProperty" value="100"/>objectFactory>
  • plugins

MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用.

<plugins><plugin interceptor="org.mybatis.example.ExamplePlugin">  <property name="someProperty" value="100"/>plugin>plugins>
  • environments

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中使用相同的 SQL 映射。还有许多类似的使用场景。

<environments default="development"><environment id="development">  <transactionManager type="JDBC">    <property name="..." value="..."/>  transactionManager>  <dataSource type="POOLED">    <property name="driver" value="${driver}"/>    <property name="url" value="${url}"/>    <property name="username" value="${username}"/>    <property name="password" value="${password}"/>  dataSource>environment>environments>
  • databaseIdProvider

MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。MyBatis 会加载带有匹配当前数据库 databaseId 属性和所有不带 databaseId 属性的语句。如果同时找到带有 databaseId 和不带 databaseId 的相同语句,则后者会被舍弃。

type="DB_VENDOR" />
  • typeAliases

类型别名可为 Java 类型设置一个缩写名字。它仅用于 XML 配置,意在降低冗余的全限定类名书写。

alias=alias=alias=alias=alias=alias=
  • typeHandlers

MyBatis 在设置预处理语句(PreparedStatement)中的参数或从结果集中取出一个值时, 都会用类型处理器将获取到的值以合适的方式转换成 Java 类型

<typeHandlers>  <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>  <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="java.math.RoundingMode"/>typeHandlers>
  • mappers

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等.

<mappers><mapper resource="org/mybatis/builder/AuthorMapper.xml"/><mapper resource="org/mybatis/builder/BlogMapper.xml"/><mapper resource="org/mybatis/builder/PostMapper.xml"/>mappers><mappers><mapper url="file:///var/mappers/AuthorMapper.xml"/><mapper url="file:///var/mappers/BlogMapper.xml"/><mapper url="file:///var/mappers/PostMapper.xml"/>mappers><mappers><mapper class="org.mybatis.builder.AuthorMapper"/><mapper class="org.mybatis.builder.BlogMapper"/><mapper class="org.mybatis.builder.PostMapper"/>mappers><mappers><package name="org.mybatis.builder"/>mappers>

下面来看看mapper解析的源码

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");      // 处理 resource 类型      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();      } else if (resource == null && url != null && mapperClass == null) {      // 处理 url 类型        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) {      // 处理 mapperClass 的类型        Class> mapperInterface = Resources.classForName(mapperClass);        configuration.addMapper(mapperInterface);      } else {        throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");      }    }  }}}

再来看看处理包的mapper加载过程

public void addMappers(String packageName) {  addMappers(packageName, Object.class);} public void addMappers(String packageName, Class> superType) {ResolverUtil> resolverUtil = new ResolverUtil>();resolverUtil.find(new ResolverUtil.IsA(superType), packageName);Setextends Class>>> mapperSet = resolverUtil.getClasses();// 遍历包的所有类,注册到 mappers 中for (Class> mapperClass : mapperSet) {  addMapper(mapperClass);}}public void addMapper(Classtype) {// 只处理 mapper 接口  if (type.isInterface()) {    if (hasMapper(type)) {      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");    }    boolean loadCompleted = false;    try {    //重点:根据 class 类型,创建出 mapper 的代理类工厂,保存到 knownMappers 中      knownMappers.put(type, new MapperProxyFactory(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.      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);      parser.parse();      loadCompleted = true;    } finally {      if (!loadCompleted) {        knownMappers.remove(type);      }    }  }} // 代理类工厂public class MapperProxyFactory {private final Class mapperInterface;private final Map methodCache = new ConcurrentHashMap();public MapperProxyFactory(Class mapperInterface) {  this.mapperInterface = mapperInterface;}public Class getMapperInterface() {  return mapperInterface;}public Map getMethodCache() {  return methodCache;}@SuppressWarnings("unchecked")protected T newInstance(MapperProxy mapperProxy) {  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);}// 通过 sqlSession 初始化出 MapperProxy 类,用于代理 mapper 接口的方法,进行执行CRUD等操作public T newInstance(SqlSession sqlSession) {  final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);  return newInstance(mapperProxy);}}

3. 总结

mybatis的初始化过程中,config 配置文件是最重要的,这是告诉 mybatis 的加载过程,需要加载的数据,mybatis也提供了丰富的功能,如拦截器,插件,类型转换等,mapper的创建重点在与代理类,通过代理设计模式创建出 mapper,代替接口的注释或xml的mapper进行CRUD操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值