Mybatis与Spring集成时都做了什么?
本篇主旨介绍
Mybatis是java开发者非常熟悉的ORM框架,Spring集成Mybatis更是我们的日常开发姿势。
本篇主要讲Mybatis与Spring集成所做的事情,让读过本文的开发者对Mybatis和Spring的集成过程,有清晰的理解。
注:若文中有错误或其他疑问,欢迎留下评论。
以mybatis-spring-2.0.2 为例,工程划分六个模块。
模块介绍
1、annotation 模块
定义了@MapperScan和@MapperScans,用于扫描mapper接口。以及mapper扫描注册器(MapperScannerRegistrar),扫描注册器实现了 ImportBeanDefinitionRegistrar接口, 在Spring容器启动时会运行所有实现了这个接口的实现类,
注册器内部会注册一系列MyBatis相关Bean。
2、batch 模块
批处理相关,基于优秀的批处理框架Spring batch 封装了三个批处理相关类:
MyBatisBatchItemWriter(批量写)
MyBatisCursorItemReader(游标读)
MyBatisPagingItemReader(分页读)
在使用Mybatis时,方便的应用Spring batch,详见 Spring-batch使用。
3、config模块
解析、处理读取到的配置信息。
4、mapper模块
这里是处理mapper的地方:ClassPathMapperScanner(根据路径扫描Mapper接口)与MapperScannerConfigurer 配合,完成批量扫描mapper接口并注册为MapperFactoryBean。
5、support 模块
支持包,SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession调用getSqlSession()方法会得到一个SqlSessionTemplate。
6、transaction 模块,以及凌乱类
与Spring集成后,事务管理交由Spring来做。
还有包括异常转换,以及非常重要的SqlSessionFactoryBean,在外散落着。
下面重点讲述几个核心部分:
一、初始化相关
1) SqlSessionFactoryBean
在基础的MyBatis中,通过SqlSessionFactoryBuilder创建SqlSessionFactory。集成Spring后由SqlSessionFactoryBean来创建。
public class SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
需要注意SqlSessionFactoryBean实现了Spring的FactoryBean接口。这意味着由Spring最终创建不是SqlSessionFactoryBean本身,而是 getObject()的结果。我们来看下getObject()
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
//配置加载完毕后,创建SqlSessionFactory
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
getObject()最终返回了当前类的 SqlSessionFactory,因此,Spring 会在应用启动时创建 SqlSessionFactory,并以 sqlSessionFactory名称放进容器。
2) 两个重要属性
1. SqlSessionFactory 有一个唯一的必要属性:用于 JDBC 的 DataSource不能为空,这点在afterPropertisSet()中体现。
2. configLocation,它用来指定 MyBatis 的 XML 配置文件路径。通常只用来配置 <settings>相关。其他均使用Spring方式配置
public void afterPropertiesSet() throws Exception {
//dataSource不能为空
notNull(dataSource, "Property 'dataSource' is required");
//有默认值,初始化 = new SqlSessionFactoryBuilder()
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
//判断configuration && configLocation有且仅有一个
state((configuration == null && configLocation == null) ||
!(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
//调用build方法创建sqlSessionFactory
this.sqlSessionFactory = buildSqlSessionFactory();
}
buildSqlSessionFactory()方法比较长所以,这里省略了一部分代码,只展示主要过程,看得出在这里进行了Mybatis相关配置的
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
final Configuration targetCon