Mybatis的源码学习(一):

 前言:

 结合spring本次学习会先从spring-mybatis开始分析

  在学习mybatis之前,应该要对spring的bean有所了解,本文略过

  先贴一下mybatis的配置:

 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations">
<array>
<value>classpath:mapper/**/*.xml</value>
</array>
</property>
<property name="typeAliasesPackage" value="xxxx.model"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
 <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="xxxx.mapper"/>
</bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

先看第一个配置,配置

<property name="dataSource" ref="dataSource"/>

这段即spring IOC 依赖注入的特性,将数据库的配置信息设置到该set方法中

        <property name="mapperLocations">
<array>
<value>classpath:mapper/**/*.xml</value>
</array>
</property>

该属性是扫描mapper的xml配置

 <property name="typeAliasesPackage" value="xxxx.model"/>

这个配置即为model(或者entity/domain)类设置别名

<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
</value>
</property>
</bean>
</array>
</property>

这个配置是集成了分页的pahelper插件,

配置看完了,现在就开始看java代码了

配置好项目之后,找到SqlSessionFactoryBean然后启动tomcat,为什么要找这个类呢?因为这个类就是spring注入mabatis属性的一个入口(将mybatis和spring整合)

结合上面配置内容

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

底下的所有操作都是为Configuration设置塞值,为了不影响篇幅冗余,暂且略过这些

说一下下面这句

扫描注册Mapper接口

在初始化的时候已经将mapper解析xml的时候已经将mapper注册为一个mapper bean 了
 完成上述操作之后,mapper下的所有接口都已经与xml的namespace匹配上,并且mapper注册为一个代理类

最后一句代码就完成转化

调试到 SqlSessionFactoryBuilder,发现默认创建了 DefaultSqlSessionFactory

建立了sqlSessionFactory

下来是扫描

<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">

看一下这个类的继承关系

我们看到了这个类实现了BeanDefinitionRegistryPostProcessor接口,此接口即动态的将Bean的内容进行动态修改

方法实现即在下方

执行完上面那个方法之后,tk-mapper开始往下执行,由于一开始spring在扫描sqlSessionFactoryBuilder的时候就已经把mapper命名空间什么的已经扫描过,所以这块不会再去注册mapperBean

下面的注册mapper接口在前面已经执行过了

接下来注入sqlSession模板类,这个类是通过动态代理的方式获取执行器并执行sql

看下配置

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

spring开始扫描这个配置,打开调试器,看一下SqlSessionTemplate的继承图

它继承了SqlSession接口,还有一个SqlSession对象?这个是什么操作?

看构造方法,原来作者这样的设计是让 sqlSessionProxy代理  对SqlSession进行操作

  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
//代理对象创建执行器,并连接DB进行操作
this.sqlSessionProxy = (SqlSession) newProxyInstance(
SqlSessionFactory.class.getClassLoader(),
new Class[] { SqlSession.class },
new SqlSessionInterceptor());
}
 /**
* Proxy needed to route MyBatis method calls to the proper SqlSession got
* from Spring's Transaction Manager
* It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to
* pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}.
*/
private class SqlSessionInterceptor implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   //这里的实际对象是DefaultSqlSession
SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
     //执行目标方法(即调用Executor并组装成sql进行db操作)
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
// release the connection to avoid a deadlock if the translator is no loaded. See issue #22
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
sqlSession = null;
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
if (sqlSession != null) {
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
}

不得不说,作者的设计架构是真的很棒

下一文 说一下mybatis的动态代理

Spring,tk-mapper源码阅读的更多相关文章

  1. Spring 注册BeanPostProcessor 源码阅读

    回顾上一篇博客中,在AbstractApplicationContext这个抽象类中,Spring使用invokeBeanFactoryPostProcessors(beanFactory);执行Be ...

  2. spring framework 4 源码阅读(1) --- 前期准备

    在开始看代码之前,需要做的第一件事是下载代码. 在这里:https://github.com/spring-projects/spring-framework 下载完成了发现使用gradle做的源代码 ...

  3. spring framework 4 源码阅读

    前面写了几篇spring 的介绍文章,感觉与主题不是很切合.重新整理下思路,从更容易理解的角度来写下文章. spring 的骨架 spring 的骨架,也是spring 的核心包.主要包含三个内容 1 ...

  4. spring framework 4 源码阅读(2)---从ClassPathXmlApplicationContext开始

    Application初始化日志 15:23:12.790 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperti ...

  5. (转) Spring源码阅读 之 Spring整体架构

    标签(空格分隔): Spring 声明:本文系转载,原地地址:spring framework 4 源码阅读 Spring骨架 Spring的骨架,也是Spring的核心包.主要包含三个内容 cont ...

  6. Sping学习笔记(一)----Spring源码阅读环境的搭建

    idea搭建spring源码阅读环境 安装gradle Github下载Spring源码 新建学习spring源码的项目 idea搭建spring源码阅读环境 安装gradle 在官网中下载gradl ...

  7. Spring源码阅读系列总结

    最近一段时间,粗略的查看了一下Spring源码,对Spring的两大核心和Spring的组件有了更深入的了解.同时在学习Spring源码时,得了解一些设计模式,不然阅读源码还是有一定难度的,所以一些重 ...

  8. Bean实例化(Spring源码阅读)-我们到底能走多远系列(33)

    我们到底能走多远系列(33) 扯淡: 各位:    命运就算颠沛流离   命运就算曲折离奇   命运就算恐吓着你做人没趣味   别流泪 心酸 更不应舍弃   ... 主题: Spring源码阅读还在继 ...

  9. 初始化IoC容器(Spring源码阅读)

    初始化IoC容器(Spring源码阅读) 我们到底能走多远系列(31) 扯淡: 有个问题一直想问:各位你们的工资剩下来会怎么处理?已婚的,我知道工资永远都是不够的.未婚的你们,你们是怎么分配工资的? ...

  10. Spring事务源码阅读笔记

    1. 背景 本文主要介绍Spring声明式事务的实现原理及源码.对一些工作中的案例与事务源码中的参数进行总结. 2. 基本概念 2.1 基本名词解释 名词 概念 PlatformTransaction ...

随机推荐

  1. 转:概率主题模型简介 --- ---David M. Blei所写的《Introduction to Probabilistic Topic Models》的译文

    概率主题模型简介 Introduction to Probabilistic Topic Models      转:http://www.cnblogs.com/siegfang/archive/2 ...

  2. 【以前的空间】BZOJ2733[HNOI2012]永无乡

    启发式合并?! 似乎当时写并查集的时候就有看到过类似于把小并查集并到大并查集上的说法,原来这就是启发式…… 具体做法就是把小树里面的一个个拿出来,然后加到大树里面去(裸的不敢相信) const max ...

  3. Spark2.1.0之初识Spark

    随着近十年互联网的迅猛发展,越来越多的人融入了互联网——利用搜索引擎查询词条或问题:社交圈子从现实搬到了Facebook.Twitter.微信等社交平台上:女孩子们现在少了逛街,多了在各大电商平台上的 ...

  4. BZOJ4753:[JSOI2016]最佳团体——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=4753 JSOI信息学代表队一共有N名候选人,这些候选人从1到N编号.方便起见,JYY的编号是0号. ...

  5. BZOJ3534:[SDOI2014]重建——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=3534 https://www.luogu.org/problemnew/show/P3317 T国 ...

  6. LOJ6303:水题——题解

    https://loj.ac/problem/6303 题目来自LOJ. 就记一个公式,设f(n,k)为n!里分解得到的k(k为质数)的个数,则f(n,k)=f(n/k,k)+n/k. 证明很好证,显 ...

  7. BZOJ2186 [Sdoi2008]沙拉公主的困惑 【数论,欧拉函数,线性筛,乘法逆元】

    2186: [Sdoi2008]沙拉公主的困惑 Time Limit: 10 Sec  Memory Limit: 259 MB Submit: 5003  Solved: 1725 [Submit] ...

  8. JavaScript URL汉字编码转换

    在使用url进行参数传递时,经常会传递一些中文名的参数或URL地址,在后台处理时会发生转换错误.在有些传递页面使用GB2312,而在接收页面使用UTF8,这样接收到的参数就可能会与原来发生不一致.使用 ...

  9. 中国MOOC_面向对象程序设计——Java语言_第3周 对象容器_1查找里程

    第3周编程题 查看帮助 返回   第3周编程题.注意程序(包括注释)中不能出现汉字. 依照学术诚信条款,我保证此作业是本人独立完成的. 温馨提示: 1.本次作业属于Online Judge题目,提交后 ...

  10. 集成淘宝sdk

    204是安全图片的问题, 请先检测以下几点: .请检测百川控制台是否已经申请初级API. .请检测百川控制台“我的产品后台”是否开通电商SDK应用.(重点检测很多用户疏忽这一点) .debug版本的可 ...