文章目录
前言
提示:此文章适合正在读源码的同仁,主要包含了一些源码中的设计思路及关键点,初略概述
一、处理流程
1.解析mybatis-config.xml文件封装configuration对象
主要类
- XPath
用来解析document对象,将xml解析生成的document对象解析成一个个节点对象(树形结构)便于后续面向对象编程 - Configuration
mybatis的主要配置类,里边包含了mybatis解析到的所有配置文件缓存在该对象中; - MapperRegistry
mapper注册器,主要包含两个方法:addMapper/getMapper,addMapper会完成对mapp文件的解析操作;knownMappers属性用来创建动态代理类; - MapperProxy
mapper接口代理类拦截器,实现了InvocationHandler方法,在动态代理时会先调用该类的invoke方法进行增强, - MapperMethod
- 动态代理调用invoke方法,会调用到对应mapper动态代理对应的MapperMethod方法进行execute方法真正执行后续数据库的操作
- SqlSessionFactoryBuilder
使用构造者模式构建SqlSessionFactory对象 - SqlSessionFactory
用于创造构建并创造sqlSession对象; - SqlSession
mybatis操作数据库的接口,用来执行SQL,获取映射器,管理事务。一般使用DefaultSqlSession实现类
主要代码
// 解析mybatis-config.xml文件
public Configuration parse() {
// 根据parsed变量的值判断是否已经完成了对mybatis-config.xml配置文件的解析
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
// 在mybatis-config.xml配置文件中查找<configuration>节点,并开始解析
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
// 解析配置
private void parseConfiguration(XNode root) {
try {
// issue #117 read properties first
// 解析properties
propertiesElement(root.evalNode("properties"));
// 解析settings
Properties settings = settingsAsProperties(root.evalNode("settings"));
// 设置vfsImpl字段
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);//设置具体的属性到configuration对象
// read it after objectFactory and objectWrapperFactory issue #631
// 环境
environmentsElement(root.evalNode("environments"));
// databaseIdProvider
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);
}
}
// 解析mapper.xml
public void parse() {
// 判断是否已经加载过该映射文件
if (!configuration.isResourceLoaded(resource)) {
// 处理mapper节点
configurationElement(parser.evalNode("/mapper"));
// 将resource添加到Configuration.loadedResources集合中保存,他是hashset类型的集合,其中记录了已经加载过的映射文件
configuration.addLoadedResource(resource);
// 绑定映射器到namespace
bindMapperForNamespace();
}
// 处理ConfigurationElement方法中解析失败的resultMap节点
parsePendingResultMaps();
// 处理ConfigurationElement方法中解析失败的cache-ref节点
parsePendingCacheRefs();
// 处理ConfigurationElement方法中解析失败的SQL语句节点
parsePendingStatements();
}
private void configurationElement(XNode context) {
try {
// 获取mapper节点的namespace属性
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.isEmpty()) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
// 设置MapperBuilderAssistant的currentNamespace字段,记录当前命名空间
builderAssistant.setCurrentNamespace(namespace);
// 解析cache-ref节点
cacheRefElement(context.evalNode("cache-ref"));
// 解析cache节点
cacheElement(context.evalNode("cache"));
// 解析parameterMap节点
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析resultMap节点
resultMapElements(context.evalNodes("/mapper/resultMap"));
// 解析sql节点
sqlElement(context.evalNodes("/mapper/sql"));
// 解析select、update、insert、delete等SQL节点
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
}
}
2.抽象流程
3.调用方法执行数据库操作抽象流程
4.二级缓存
5.全局流程
6.Spring整合mybatis
- 配置文件分析
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--数据库配置信息,写在一个单独的文件里,执行文件的路径-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--声明数据源DataSource,作用是连接数据库-->
<bean id="MyDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url"
value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--连接池最多可以连接多少数据库,默认20-->
<property name="maxActive" value="20"/>
</bean>
<!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,把数据库连接池赋给了dataSource属性-->
<property name="dataSource" ref="MyDataSource"/>
<!--
mybatis主配置文件的位置,因为是在spring中指定mybatis主配置文件,所以要用classpath:
configLocation:属性是Resource类型的,负责读取配置文件
赋值使用 value 指定文件的路径
-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定SqlSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
<!--指定包名,包名是dao接口的包名
MapperScannerConfigurer会扫描这个包中所有的接口,
把每个接口都执行一次getMapper()方法,得到每个接口的dao对象
创建好的dao对象放入spring容器中
创建好的dao对象名称就是接口名首字母小写,例如studentDao
-->
<property name="basePackage" value="com.luhb.dao"/>
</bean>
<!--声明Service-->
<bean id="empService" class="com.luhb.service.impl.EmpServiceImpl">
<property name="empDao" ref="empDao"/>
</bean>
</beans>
比较主要的两个配置是SqlSessionFactoryBean,MapperScannerConfigurer
- SqlSessionFactoryBean:是一个实现了FactoryBean接口的复杂对象,spring会通过调用其getObject方法来构建sqlSessionFactory对象,包含了对config对象的初始化,对xml文件的解析操作;
- MapperScannerConfigurer:原始的mybatis想要通过mapper接口来执行mapper.xml文件的sql是通过调用 sqlSession.getMapper来获取代理类的,sping为了避免每使用一个mapper接口就要动态代理一次mapper接口操作,引入MapperScannerConfigurer来在spring项目启动时就直接对mapper接口进行动态代理操作;
- 流程分析