Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的)。

Mybatis支持对ExecutorStatementHandlerParameterHandlerResultSetHandler进行拦截。

插件的运行时的逻辑:

  1. 所有可能被拦截的处理类都会生成一个代理。
  2. 代理类在执行对应方法时,判断要不要执行插件中的拦截方法。
  3. 执行插件中的拦截方法后,推进目标的执行。

Executor

前面博客介绍过Executor是在openSession()的过程中被创建的。在调用ConfigurationnewExecutor()方法创建Executor时会进行以下操作。

1
executor = (Executor) interceptorChain.pluginAll(executor);

每一个拦截器对目标类都进行一次代理,层层进行。

executor执行了多次plugin,第一次plugin后通过Plugin.wrap方法生成了第一个代理类,姑且就叫executorProxy1,这个代理类的target属性是该executor对象。第二次plugin后通过Plugin.wrap方法生成了第二个代理类,姑且叫executorProxy2,这个代理类的target属性是executorProxy1…这样通过每个代理类的target属性就构成了一个代理链。

InterceptorChain
1
2
3
4
5
6
public Object (Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}

Interceptor

拦截器Interceptor接口定义了三个方法:

  • intercept(): 内部要通过invocation.proceed()显式地推进责任链前进,也就是调用下一个拦截器拦截目标方法。
  • plugin(): 用当前这个拦截器生成对目标target的代理,实际是通过Plugin.wrap(target,this) 来完成的,把目标target和拦截器this传给了包装函数。
  • setProperties(): 用于设置额外的参数,参数配置在拦截器的Properties节点里。
自定义拦截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package plugin;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
({@Signature(
type= Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class MyPlugin implements Interceptor{
@Override
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}

Plugin

生成拦截器代理对象是在Plugin.wrap()中完成的,Plugin本身实现了InvocationHandler(JDK代理实现)。

  • target: 被代理的目标类。
  • interceptor: 对应的拦截器。
  • signatureMap: 拦截器拦截的方法缓存。

Plugin代理对象的invoke()完成对目标类的方法调用。如果方法签名和拦截中的签名一致,就调用拦截器的拦截方法intercept(),传递的是一个Invocation对象。

Plugin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Plugin implements InvocationHandler {
...
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return大专栏  Mybatis: 插件及分页pan> Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
...
}

Invocation

Invocation对象保存了代理对象的目标类,执行的目标类方法以及传递给它的参数,真正执行目标类的方法调用是在Invocation中的proceed()方法。
所以代理对象的invoke()中调用拦截器的intercept(Invocation invocation)方法后,在该方法还必须调用invocation.proceed()方法才能使代理链继续执行下去

Invocation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invocation {
private Object target;
private Method method;
private Object[] args;
...
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}

详情参见:Mybatis 插件原理

分页

Mybatis的分页功能是基于内存的分页,也就是查出所有记录再按照偏移量offset和limit取出结果。在大数据量的情况下不适用,下面两个插件都是通过拦截Executor等重写sql语句实现数据库的物理分页。

逻辑分页(内存分页)

Mybatis 自身通过 RowBounds来完成内存分页的。

Test
1
2
3
4
List<Actor> actorsInMem = mapper.selectAll(new RowBounds(10, 5));
for (Actor actor: actorsInMem){
System.out.println(actor);
}
ActorMapper
1
List<Actor> selectAll(RowBounds rowBounds);
ActorMapper.xml
1
2
3
4
5
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from actor
</select>
输出结果(第3页数据)
1
2
3
4
5
Actor{actorId=11, firstName='ZERO', lastName='CAGE', lastUpdate=Wed Feb 15 04:34:33 CST 2006}
Actor{actorId=12, firstName='KARL', lastName='BERRY', lastUpdate=Wed Feb 15 04:34:33 CST 2006}
Actor{actorId=13, firstName='UMA', lastName='WOOD', lastUpdate=Wed Feb 15 04:34:33 CST 2006}
Actor{actorId=14, firstName='VIVIEN', lastName='BERGEN', lastUpdate=Wed Feb 15 04:34:33 CST 2006}
Actor{actorId=15, firstName='CUBA', lastName='OLIVIER', lastUpdate=Wed Feb 15 04:34:33 CST 2006}

物理分页

物理分页就是在SQL查询过程中实现分页,不同的数据库厂商,实现也会不同。MySql通过在sql语句中添加offset和limit实现。

分页插件实现,通过添加拦截器,对Executor进行拦截,然后重写sql:

详情参见:Mybatis 分页

Mybatis: 插件及分页的更多相关文章

  1. Mybatis插件原理和PageHelper结合实战分页插件(七)

    今天和大家分享下mybatis的一个分页插件PageHelper,在讲解PageHelper之前我们需要先了解下mybatis的插件原理.PageHelper 的官方网站:https://github ...

  2. Springboot 系列(十二)使用 Mybatis 集成 pagehelper 分页插件和 mapper 插件

    前言 在 Springboot 系列文章第十一篇里(使用 Mybatis(自动生成插件) 访问数据库),实验了 Springboot 结合 Mybatis 以及 Mybatis-generator 生 ...

  3. SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页

    SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了. ...

  4. Mybatis中使用PageHelper插件进行分页

    分页的场景比较常见,下面主要介绍一下使用PageHelper插件进行分页操作: 一.概述: PageHelper支持对mybatis进行分页操作,项目在github地址: https://github ...

  5. springboot结合mybatis使用pageHelper插件进行分页查询

    1.pom相关依赖引入 <dependencies> <dependency> <groupId>org.springframework.boot</grou ...

  6. Mybatis的PageHelper分页插件的PageInfo的属性参数,成员变量的解释,以及页面模板

    作者:个人微信公众号:程序猿的月光宝盒 //当前页 private int pageNum; //每页的数量 private int pageSize; //当前页的数量 private int si ...

  7. Spring Boot整合tk.mybatis及pageHelper分页插件及mybatis逆向工程

    Spring Boot整合druid数据源 1)引入依赖 <dependency> <groupId>com.alibaba</groupId> <artif ...

  8. mybatis插件机制及分页插件原理

    MyBatis 插件原理与自定义插件: MyBatis 通过提供插件机制,让我们可以根据自己的需要去增强MyBatis 的功能.需要注意的是,如果没有完全理解MyBatis 的运行原理和插件的工作方式 ...

  9. 小白的springboot之路(十五)、mybatis的PageHelper分页插件使用

    0.前言 用mybatis,那么分页必不可少,基本都是用PageHelper这个分页插件,好用方便: 1.实现 1.1.添加依赖: <!-- 3.集成 mybatis pagehelper--& ...

随机推荐

  1. Java常见异常说明汇总

    1. java.lang.nullpointerexception 这个异常大家肯定都经常遇到,异常的解释是"程序遇上了空指针",简单地说就是调用了未经初始化的对象或者是不存在的对 ...

  2. Python - 文件和目录

    # -*- coding: utf-8 -*- import os print(os.name) # 获取操作系统类型 # print(os.uname()) # 获取操作系统的详细信息,Win不支持 ...

  3. istio介绍

    核心架构 解决的问题 故障排查 1.  这个请求在哪里失败了?A有调用B吗? 2.  为什么用户的请求/页面hung住了? 3.  为什么系统这么慢?那个组件最慢? 应用容错性 1.  客户端没有配置 ...

  4. day54-mysql-库、表、数据操作

    . 什么是数据库 存储数据的仓库 . 什么数据: 大家所知道的都是数据.比如:你同学的名字,年龄,性别等等 . 数据库概念 .数据库服务器 .数据库管理系统 重点 .库 .表 .记录 .数据 参考画图 ...

  5. mysql,主键与索引的区别和联系

    关系数据库依赖于主键,它是数据库物理模式的基石.主键在物理层面上只有两个用途: 惟一地标识一行. 作为一个可以被外键有效引用的对象. 索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成 ...

  6. [LC] 207. Course Schedule

    There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prereq ...

  7. 结构体struct,类class

    1.struct,值类型,结构体会自动生成初始化方法,class是引用类型 struct Person { var name : String var age : Int func simpleDes ...

  8. [Windows] Access SMBIOS

    SMBIOS architecture System Management BIOS (SMBIOS) is the premier standard for delivering managemen ...

  9. linux awk详解

    awk: awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑, awk在其对数据分析并生成报告时,显得尤为强大. 简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开 ...

  10. Office Lens:口袋中的扫描仪

    Lens:口袋中的扫描仪" title="Office Lens:口袋中的扫描仪"> 编者按:开会时,你是否觉得白板上天马行空的讨论记录誊抄起来费时费事又难以共享- ...