前几面的文章中,我们了解MyBatis的基础项目的搭建与配置,本文章中将项目的源码来讲解一下,从源码的角度上来看下MyBatis的启动源码。首先我们来看下基础的项目的代码
@Testpublic void testResource() throws IOException, SQLException {// 1.创建配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 构建 SQLSessionFactory,以创建 SqlSessionsqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();// 2、执行查询语句BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);List<UserDO> userDOS = mapper.find("A");// 关闭SessionsqlSession.close();}
构建 SqlSessionFactory
通过 new SqlSessionFactoryBuilder().build(inputStream) 可以构建一个SQLSessionFactory ,SQLSessionFactory 可以用来创建 SQLSession ,所以如何通过配置文件 创建一个 SQLSessionFactory是本短重点。
// 通过 build 构建一个 XMLConfigBuilderpublic SqlSessionFactory build(inputStream, environment, 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) {}}}
在XMLConfigBuilder 之后,通过 parse.parse() 方法进行解析配置文件
public Configuration parse() {// 从XML文件中获取根目录的 configuration 节点parseConfiguration(parser.evalNode("/configuration"));return configuration;}private void parseConfiguration(XNode root) {try {// 配置变量参数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);// 配置环境environmentsElement(root.evalNode("environments"));// 配置数据库提供商databaseIdProviderElement(root.evalNode("databaseIdProvider"));// 配置类型处理器typeHandlerElement(root.evalNode("typeHandlers"));// 配置MappermapperElement(root.evalNode("mappers"));} catch (Exception e) {throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);}}
解析 配置项(Properties)
从 MyBatis 的配置文件中就可以看出 有个标签类别为 properties 的 属性,常见的情况下,通常如下配置
<properties><property name="title" value="TITLE"/><property name="age" value="17"/></properties>
上面的代码中通过 propertiesElement(root.evalNode("properties")); 的主要作用就是解析出 propterties 标签的内容,具体的解释看注释。
private void propertiesElement(XNode context) throws Exception {// 如果配置文件中不存子 properties 字段属性,那么就不解析if (context != null) {// 获取Properties的内容,将其封装为 Properties,Properties继承了 Hashtable// 可以粗略的认为 Properties 就是一个 KV 集合Properties defaults = context.getChildrenAsProperties();// 从Properties中获取到 resource属性和URL属性,尝试从其他资源中获取配置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.");}// 根据 resource或者URL 解析到新的Properties,Put 到 上面解析的结果中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);}//设置回Parse用于后续的解析使用parser.setVariables(defaults);//设置回Configuration中configuration.setVariables(defaults);}}
通过 propertiesElement() 方法就首先得解析出配置文件中配置的变量,并用于后续其他属性解析。
配置 设置项(Settings)
接下来的是解析settings,Setting是MyBatis的相关配置项,开发者可以通过此标签进行MyBatis相关控制以及相关选项的配置。比如一个简单的配置项如下
<settings><setting name="cacheEnabled" value="false"/></settings>
其解析代码如下:
private Properties settingsAsProperties(XNode context) {if (context == null) {return new Properties();}Properties props = context.getChildrenAsProperties();// 获取支持的属性值MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);for (Object key : props.keySet()) {// 如果给定的属性值不属于 Configuration 内置的属性,则会抛出异常if (!metaConfig.hasSetter(String.valueOf(key))) {throw new BuilderException("The setting " + key + " is not known. Make sure you spelled it correctly (case sensitive).");}}return props;}
可以看到,Setting的解析如果出现未知的配置项,则会抛出异常。那么通过 Configuration 可以看到允许的配置值.
public class Configuration {protected Environment environment;protected boolean safeRowBoundsEnabled;protected boolean safeResultHandlerEnabled = true;protected boolean mapUnderscoreToCamelCase;protected boolean aggressiveLazyLoading;protected boolean multipleResultSetsEnabled = true;protected boolean useGeneratedKeys;protected boolean useColumnLabel = true;protected boolean cacheEnabled = true;protected boolean callSettersOnNulls;protected boolean useActualParamName = true;protected boolean returnInstanceForEmptyRow;protected boolean shrinkWhitespacesInSql;// .....}
在Settings 解析完成之后,会返回一个Properties 用于其他的配置,比如配置
// org/apache/ibatis/builder/xml/XMLConfigBuilder.java:107Properties settings = settingsAsProperties(root.evalNode("settings"));// 配置虚拟文件系统loadCustomVfs(settings);// 配置自定义的日志系统loadCustomLogImpl(settings);
配置 类型别名(typeAliases)
类型别名是MyBatis中非常重要的一个概念, 它能够帮助开发者更简便的编写代码。类型别名的使用方式不再本文的讨论中,比如我们配置一个简单的别名如下
<typeAliases><!-- 使用 package 的方式,按包指定--><package name="com.zhoutao123.dao.model"/><!-- 或者使用下面的方式,单个指定--><typeAlias type="org.mybatis.example.UserDO" alias="user"/></typeAliases>
那么我们在书写Mapper的时候就可以直接这样使用
<!--定义别名之前--><select id="find" resultType="org.mybatis.example.UserDO">SELECT * FROM user WHERE id = #{id}</select><!--定义别名之后--><select id="find" resultType="user">SELECT * FROM user WHERE id = #{id}</select>
可以通过 typeAliasesElement 查看类型别名的源码
if (parent != null) {for (XNode child : parent.getChildren()) {// 如果指定了按包级别扫描别名,则通过 name 属性获取到需要扫描的包下的类if ("package".equals(child.getName())) {String typeAliasPackage = child.getStringAttribute("name");configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);} else {// 如果不是按照包扫描别名则直接通过标签 typeAlias 的alias属性和 type 属性注册String alias = child.getStringAttribute("alias");String type = child.getStringAttribute("type");try {Class<?> clazz = Resources.classForName(type);// 如果别名为NULL,则根据策略生成一个alias, 生成范式参照 下面的 registerAlias(Class<?> type)if (alias == null) {typeAliasRegistry.registerAlias(clazz);} else {typeAliasRegistry.registerAlias(alias, clazz);}} catch (ClassNotFoundException e) {throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);}}}}public void registerAlias(Class<?> type) {// 获取类的简称String alias = type.getSimpleName();// 获取类上的Alias注解Alias aliasAnnotation = type.getAnnotation(Alias.class);// 如果注解存在,则使用注解的值作为别名,否则使用类的简称作为别名if (aliasAnnotation != null) {alias = aliasAnnotation.value();}registerAlias(alias, type);}
在最后,类型别名和类型的clazz 对象将被保存在 typeAlias 对象中, typeAliases 对象则是一个Map集合,用于保存 MyBatis系统中自定义的类型别名
private final Map<String, Class<?>> typeAliases = new HashMap<>();public void registerAlias(String alias, Class<?> value) {if (alias == null) {throw new TypeException("The parameter alias cannot be null");}// issue #748String key = alias.toLowerCase(Locale.ENGLISH);if (typeAliases.containsKey(key) && typeAliases.get(key) != null && !typeAliases.get(key).equals(value)) {throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + typeAliases.get(key).getName() + "'.");}typeAliases.put(key, value);}
众所周知,MyBatis 也内置一些常用的类型别名,比如 string/int/boolean/map/list 等,这些默认的别名也是通过 registerAlias 实现注册的,在 TypeAlias 的构造方法中可以看到相关的源码
public TypeAliasRegistry() {registerAlias("string", String.class);registerAlias("byte", Byte.class);registerAlias("long", Long.class);registerAlias("short", Short.class);// .... 省略部分registerAlias("map", Map.class);registerAlias("hashmap", HashMap.class);registerAlias("ResultSet", ResultSet.class);}
配置 插件(Plugin)
插件可以说是对于MyBatis 使用的一个重要的分水岭,很多非常好用的MyBatis的插件都是使用Plugin实现的,比如 PageHelp、MyBatais-Plus。下面看看Plugin的配置方式吧
<plugins><plugin interceptor="org.mybatis.example.plugins.CustomerExecutor"><property name="limit" value="123"/><property name="max" value="456"/></plugin></plugins>
上面的一段XML代码实现一个MyBatis 插件的注册 , 而插件则必须是 org.apache.ibatis.plugin.Intercepto 的子类。
由于本文主要的重点是MyBatis流程的启动过程以及MyBatis配置的解析过程,所以MyBatis的插件开发将后再后续的文章通过案例(PageHelp)以源码解析的方式学习Plugin的开发。当然后面也会实现一个简单的案例
for (XNode child : parent.getChildren()) {// 获取 <plugin> 标签的 interceptor 属性以及其属性值propertiesString interceptor = child.getStringAttribute("interceptor");Properties properties = child.getChildrenAsProperties();// 通过全类名解析出Class并获取其构造方式并创建一个新的实例Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();// 为此实例设置propertiesinterceptorInstance.setProperties(properties);// MyBatis 的 configuration中新增拦截器configuration.addInterceptor(interceptorInstance);}
配置 对象工厂(ObjectFactory)
MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过参数构造方法来实例化。 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。那么假设我们需要对创建的实体进行一些设定,就可以通过继承 org.apache.ibatis.reflection.factory.DefaultObjectFactory 的方式覆盖 其默认行为.
public class CustomerObjectFactory extends DefaultObjectFactory {@Overridepublic <T> T create(Class<T> type) {T t = super.create(type);// 构造的之后添加自定的逻辑if (t instanceof UserDO) {((UserDO) t).setId(1L);}return t;}@Overridepublic <T> T create(Class<T> type, List<Class<?>> constructorArgTypes,List<Object> constructorArgs) {return super.create(type, constructorArgTypes, constructorArgs);}@Overridepublic <T> boolean isCollection(Class<T> type) {return false;}}
其在MyBatis中的配置方式如下
<objectFactory type="org.mybatis.example.CustomerObjectFactory"><property name="name" value="CustomerObjectFactory"/></objectFactory>
而在其解析对象工厂的源码中也和插件的方式比较类似, 需要注意的是,在ObjectFactory创建完成后,其被保存在 configuration 中。
private void objectFactoryElement(XNode context) throws Exception {if (context != null) {String type = context.getStringAttribute("type");Properties properties = context.getChildrenAsProperties();ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();factory.setProperties(properties);configuration.setObjectFactory(factory);}}
这里同样的还有 objectWrapperFactory 以及 reflectorFactory 这里和ObjectFactory 都是比较类似的,读者可自行了解其解析方式。
配置 环境(Environments)
这里的环境指的MyBatis的运行环境,包括数据源以及事务管理等,环境是MyBatis非常重要的特性。日常开发中合理的使用环境将会非常的方便,我们看看在MyBatis的配置文件中如何使用环境。
<!-- 创建环境,其默认环境为 id = dev 的配置--><environments default="dev"><environment id="dev"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/><property name="username" value="root"/><property name="password" value="username123"/></dataSource></environment><environment id="prod"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.03:3306/test"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments>
运行环境的解析过程如下
private void environmentsElement(XNode context) throws Exception {if (context != null) {if (environment == null) {// 获取默认环境environment = context.getStringAttribute("default");}for (XNode child : context.getChildren()) {String id = child.getStringAttribute("id");// 如果是默认环境则进行解析,否则不解析if (isSpecifiedEnvironment(id)) {// 事务工厂TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));// 数据源DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));DataSource dataSource = dsFactory.getDataSource();Environment.Builder environmentBuilder =new Environment.Builder(id).transactionFactory(txFactory).dataSource(dataSource);configuration.setEnvironment(environmentBuilder.build());}}}}
配置 数据库厂商标识(DatabaseIdProvider)
MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。 MyBatis 会加载带有匹配当前数据库 databaseId 属性和所有不带 databaseId 属性的语句。 如果同时找到带有 databaseId 和不带 databaseId 的相同语句,则后者会被舍弃。 为支持多厂商特性,只要像下面这样在 mybatis-config.xml 文件中加入 databaseIdProvider 即可:
<databaseIdProvider type="DB_VENDOR" />
databaseIdProvider 对应的 DB_VENDOR 实现会将 databaseId 设置为 DatabaseMetaData#getDatabaseProductName() 返回的字符串。 由于通常情况下这些字符串都非常长,而且相同产品的不同版本会返回不同的值,你可能想通过设置属性别名来使其变短:
<databaseIdProvider type="DB_VENDOR"><property name="SQL Server" value="sqlserver"/><property name="DB2" value="db2"/><property name="Oracle" value="oracle" /></databaseIdProvider>
在提供了属性别名时,databaseIdProvider 的 DB_VENDOR 实现会将 databaseId 设置为数据库产品名与属性中的名称第一个相匹配的值,如果没有匹配的属性,将会设置为 “null”。 在这个例子中,如果 getDatabaseProductName() 返回“Oracle (DataDirect)”,databaseId 将被设置为“oracle”。在下面的示例中,我么可以为相同ID的 SELECT 配置不同的 databaseId.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zhoutao123.source.mybatis.mapper.UserMapper"><!-- 使用 MySQL 数据库的时候--><select id="getOneById" resultType="user" databaseId="mysql">SELECT *FROM userWHERE id = #{id}</select><!-- 使用 Oracle 数据库的时候--><select id="getOneById" resultType="user" databaseId="oracle">SELECT *FROM USERWHERE ID = #{id}</select></mapper>
其解析的过程为
private void databaseIdProviderElement(XNode context) throws Exception {DatabaseIdProvider databaseIdProvider = null;if (context != null) {String type = context.getStringAttribute("type");// awful patch to keep backward compatibilityif ("VENDOR".equals(type)) {type = "DB_VENDOR";}Properties properties = context.getChildrenAsProperties();databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();databaseIdProvider.setProperties(properties);}Environment environment = configuration.getEnvironment();if (environment != null && databaseIdProvider != null) {String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());configuration.setDatabaseId(databaseId);}}
配置 映射器(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><!-- 使用完全限定资源定位符(URL) --><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>
这些配置会告诉 MyBatis 去哪里找映射文件,剩下的细节就应该是每个 SQL 映射文件了,也就是接下来我们要重点讨论的通过动态代理的方式实现 Mapper 的访问和构造。
