一、Interceptor介绍

Mybatis 允许用户使用自定义拦截器对SQL语句执行过程中的某一点进行拦截。默认情况,可以拦截的方法如下:

  1. Executor 中的 update()、query()、flushStatement()、commit()、rollback()、getTransaction()、close()、isClosed()方法。
  2. ParameterHandler 中的getParameterObject()方法、setParameters()方法。
  3. ResultSetHandler 中的 handleResultSets()方法、handleOutputParameters()方法。
  4. StatementHandler 中的 prepare() 方法、parameterize()方法、batch()方法、update()方法、query()方法。

Interceptor接口如下:

public interface Interceptor {
// 执行拦截逻辑的方法
Object intercept(Invocation invocation) throws Throwable;
// 决定是否触发intercept()方法
Object plugin(Object target);
// 根据配置初始化Interceptor对象
void setProperties(Properties properties); }

setProperties()方法可以加载mybatis-config.xml配置文件中配置的属性,例如:

  1. <plugins> 

  2. <plugin interceptor="cn.sp.interceptor.PageInterceptor"> 

  3. <property name="testProp" value="100"></property> 

  4. </plugin> 

  5. </plugins> 

用户自定义拦截器的plugin()方法可以使用Mybatis提供的Plugin工具类实现,它实现了InvocationHandler接口,并提供了一个wrap()静态方法用于创建代理对象。

用户自定义的拦截器除了要实现Interceptor接口外,还需要使用 @Intercepts 和 @Signature 注解。

@Intercepts注解中是一个@Signature列表,每个@Signature注解都标识了该插件需要拦截的方法的信息,其中type表示需要拦截的类型,method属性指定具体的方法名,args属性指定了被拦截方法的参数列表。通过这三个属性值就可以表示一个方法签名。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
Class<?> type(); String method(); Class<?>[] args();
}

二、实现PageInterceptor

2.1Mybatis的默认分页机制

Mybatis本身可以使用RowBounds方式进行分页,但是在 DefaultResultSetHandler 中它用的是查询所有数据,然后调用ResultSet.absoulte()方法或循环调用ResultSet.next()方法定位到指定的记录行。这种基于内存分页的方式,当表中的数据量比较大时,会查询全表导致性能问题。

还有一个就是写SQL基于limit实现的物理分页,但是这种基于 "limit offset,length" 的方式如果offset的值很大时,也会导致性能很差,有时间再详细说说mysql分页部分。

下面的例子就是通过自定义拦截器实现物理分页。

2.2代码部分

搭建一个整合Mybatis的SpringBoot项目很简单,过程我就省略了。

PersonDao

public interface PersonDao {

  List<Person> queryPersonsByPage(RowBounds rowBounds);
}

PersonMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 

  3. <mapper namespace="cn.sp.dao.PersonDao" > 


  4. <select id="queryPersonsByPage" resultType="cn.sp.bean.Person"> 

  5. select * from person ORDER BY id DESC 

  6. </select> 

  7. </mapper> 

PageInterceptor

/**
* 利用拦截器实现分页
* Created by 2YSP on 2019/7/7.
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class})
})
@Slf4j
public class PageInterceptor implements Interceptor { /**
* Executor.query()方法中,MappedStatement对象在参数列表中的索引位置
*/
private static int MAPPEDSTATEMENT_INDEX = 0; /**
* 用户传入的实参对象在参数列表中的索引位置
*/
private static int PARAMTEROBJECT_INDEX = 1;
/**
* 分页对象在参数列表中的索引位置
*/
private static int ROWBOUNDS_INDEX = 2; /**
* 执行拦截逻辑的方法
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 参数列表
Object[] args = invocation.getArgs();
final MappedStatement mappedStatement = (MappedStatement) args[MAPPEDSTATEMENT_INDEX];
final Object parameter = args[PARAMTEROBJECT_INDEX];
final RowBounds rowBounds = (RowBounds) args[ROWBOUNDS_INDEX];
// 获取offset,即查询的起始位置
int offset = rowBounds.getOffset();
int limit = rowBounds.getLimit();
// 获取BoundSql对象,其中记录了包含"?"占位符的SQL语句
final BoundSql boundSql = mappedStatement.getBoundSql(parameter);
// 获取BoundSql中记录的SQL语句
String sql = boundSql.getSql();
sql = getPagingSql(sql, offset, limit);
log.info("==========sql:\n" + sql);
// 重置RowBounds对象
args[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
// 根据当前语句创建新的MappedStatement
args[MAPPEDSTATEMENT_INDEX] = createMappedStatement(mappedStatement, boundSql, sql);
// 通过Invocation.proceed()方法调用被拦截的Executor.query()方法
return invocation.proceed();
} private Object createMappedStatement(MappedStatement mappedStatement, BoundSql boundSql,
String sql) {
// 创建新的BoundSql对象
BoundSql newBoundSql = createBoundSql(mappedStatement, boundSql, sql);
Builder builder = new Builder(mappedStatement.getConfiguration(), mappedStatement.getId(),
new BoundSqlSqlSource(newBoundSql), mappedStatement.getSqlCommandType());
builder.useCache(mappedStatement.isUseCache());
builder.cache(mappedStatement.getCache());
builder.databaseId(mappedStatement.getDatabaseId());
builder.fetchSize(mappedStatement.getFetchSize());
builder.flushCacheRequired(mappedStatement.isFlushCacheRequired()); builder.keyColumn(delimitedArrayToString(mappedStatement.getKeyColumns()));
builder.keyGenerator(mappedStatement.getKeyGenerator());
builder.keyProperty(delimitedArrayToString(mappedStatement.getKeyProperties())); builder.lang(mappedStatement.getLang());
builder.resource(mappedStatement.getResource()); builder.parameterMap(mappedStatement.getParameterMap());
builder.resultMaps(mappedStatement.getResultMaps());
builder.resultOrdered(mappedStatement.isResultOrdered());
builder.resultSets(delimitedArrayToString(mappedStatement.getResultSets()));
builder.resultSetType(mappedStatement.getResultSetType()); builder.timeout(mappedStatement.getTimeout());
builder.statementType(mappedStatement.getStatementType()); return builder.build(); } public String delimitedArrayToString(String[] array) {
String result = "";
if (array == null || array.length == 0) {
return result;
}
for (int i = 0; i < array.length; i++) {
result += array[i];
if (i != array.length - 1) {
result += ",";
}
}
return result;
} class BoundSqlSqlSource implements SqlSource { private BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
} @Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
} private BoundSql createBoundSql(MappedStatement mappedStatement, BoundSql boundSql, String sql) {
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
return newBoundSql;
} /**
* 重写sql
*/
private String getPagingSql(String sql, int offset, int limit) {
sql = sql.trim();
boolean hasForUpdate = false;
String forUpdatePart = "for update";
if (sql.toLowerCase().endsWith(forUpdatePart)) {
// 将当前SQL语句的"for update片段删除"
sql = sql.substring(0, sql.length() - forUpdatePart.length());
hasForUpdate = true;
} StringBuilder result = new StringBuilder();
result.append(sql);
result.append(" limit ");
result.append(offset);
result.append(",");
result.append(limit); if (hasForUpdate) {
result.append(" " + forUpdatePart);
}
return result.toString();
} /**
* 决定是否触发intercept()方法
*/
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} /**
* 根据配置初始化Interceptor对象
*/
@Override
public void setProperties(Properties properties) {
log.info("properties: " + properties.getProperty("testProp"));
}
}

这里的思路就是拦截 query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) 方法或query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) 方法,通过RowBounds对象获得所需记录的offset和limit,通过BoundSql获取待执行的sql语句,最后重写SQL语句加入"limit offset,length"实现分页。

三、测试

执行如下测试方法:

分页测试

控制台显示结果:

enter description here

输出结果是,id为7的王五和id为6的张三,再对比数据库数据。

enter description here

最后得出结论成功实现分页查询,GitHub上开源的大名鼎鼎的PageHelper也是利用拦截器插件实现的,有时间要再看下它的源码实现。

本文代码点击这里

Mybatis利用Intercepter实现物理分页的更多相关文章

  1. spring+mybatis利用interceptor(plugin)兑现数据库读写分离

    使用spring的动态路由实现数据库负载均衡 系统中存在的多台服务器是"地位相当"的,不过,同一时间他们都处于活动(Active)状态,处于负载均衡等因素考虑,数据访问请求需要在这 ...

  2. Mybatis利用拦截器做统一分页

    mybatis利用拦截器做统一分页 查询传递Page参数,或者传递继承Page的对象参数.拦截器查询记录之后,通过改造查询sql获取总记录数.赋值Page对象,返回. 示例项目:https://git ...

  3. springboot整合mybatis,利用mybatis-genetor自动生成文件

    springboot整合mybatis,利用mybatis-genetor自动生成文件 项目结构: xx 实现思路: 1.添加依赖 <?xml version="1.0" e ...

  4. mybatis: 利用多数据源实现分库存储

    之前写过一篇mybatis 使用经验小结 提到过多数据源的处理方式,虽然简单但是姿势不太优雅,今天介绍一些更美观的办法: spring中有一个AbstractRoutingDataSource的抽象类 ...

  5. Mybatis pageHelper.startPage(...)是物理分页

    使用PageHelper.startPage(...)进行物理分页 业务需求只显示其中的100条数据 之前是在业务逻辑里对参数limit进行了处理 后来试试sql的limit查询100条数据 但是不确 ...

  6. spring 整合 mybatis (不含物理分页)

    http://www.mybatis.org/spring/mappers.html http://www.mybatis.org/spring/zh/mappers.html <?xml ve ...

  7. Spring+SpringMVC+Mybatis 利用AOP自定义注解实现可配置日志快照记录

    http://my.oschina.net/ydsakyclguozi/blog/413822

  8. mybatis利用generator自动生成的代码

    /** * 排序规则 */ protected String orderByClause; /** * 去重规则 */ protected boolean distinct; /** * where条 ...

  9. MyBatis的笔记

    1.#{}和${}的区别是什么? #{}是预编译处理,${}是字符串替换. #{}是sql的参数占位符,${}是Properties文件中的变量占位符,它可以用于标签属性值和sql内部,属于静态文本替 ...

随机推荐

  1. python实现自动发邮件

    Python有两个内置库:smtplib和email,可以实现邮件功能,无需下载,直接import导入. smtplib库负责发送邮件 Email库负责构造邮件格式和内容 邮件发送需要遵守SMTP协议 ...

  2. 转:【Python3网络爬虫开发实战】3.1.2-处理异常

    [摘要] 前一节我们了解了请求的发送过程,但是在网络不好的情况下,如果出现了异常,该怎么办呢?这时如果不处理这些异常,程序很可能因报错而终止运行,所以异常处理还是十分有必要的. urllib的erro ...

  3. 第12.4节 Python伪随机数数生成器random模块导览

    random模块实现了各种分布的伪随机数生成器,常用功能包括: random.seed(a=None, version=2):初始化随机数生成器,如果 a 被省略或为 None ,则使用当前系统时间. ...

  4. crawlergo动态爬虫去除Spidername使用

    本来是想用AWVS的爬虫来联动Xray的,但是需要主机安装AWVS,再进行规则联动,只是使用其中的目标爬虫功能感觉就太重了,在github上面找到了由360 0Kee-Team团队从360天相中分离出 ...

  5. Redis数据库简介

    最近的项目需要用到Redis数据库和MySQL,恶补学习. Redis的使用手册可以看: https://redis.io/ https://www.runoob.com/redis/redis-tu ...

  6. python冒泡算法联系代码

    root@(none):~/python# python maopao.py[6, 11, 13, 22, 99]root@(none):~/python# cat maopao.py #!/usr/ ...

  7. 软工项目WordCount

    1.Github项目地址:https://github.com/JameMo/WordCount-for-C        2.在程序的各个模块的开发上耗费的时间: PSP2.1 Personal S ...

  8. 没有它你的DevOps是玩不转的,你信不?

    摘要:架构的选择对于DevOps的实践是至关重要的,从某种程度上来说,架构就是DevOps这场战役的粮草,它是支撑着DevOps成功落地的重要前提. 善用兵者,役不再籍,粮不三载.取用于国,因粮于敌, ...

  9. 【APIO2018】选圆圈(平面分块 | CDQ分治 | KDT)

    Description 给定平面上的 \(n\) 个圆,用三个参数 \((x, y, R)\) 表示圆心坐标和半径. 每次选取最大的一个尚未被删除的圆删除,并同时删除所有与其相切或相交的圆. 最后输出 ...

  10. Angular:组件之间的通信@Input、@Output和ViewChild

    ①父组件给子组件传值 1.父组件: ts: export class HomeComponent implements OnInit { public hxTitle = '我是首页的头部'; con ...