Mybatis分页插件梳理

所有的框架都支持插件,我们可以用插件编写来扩展我们自己需要的功能,mybatis也不例外。因此,本文将从插件配置、插件编写、插件运行原理,插件注册与执行时机、初始化插件、分页插件原理来梳理说明。

插件配置

mybatis的分页插件配置在mybatis的构造器configuration,我们在初始化mybatis的时候就会独去这些插件,并且放到mybatis的拦截链InterceptorChain中,如:

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<plugins>

<plugin interceptor="com.mybatis3.interceptor.MyBatisInterceptor">

<property name="value" value="100" />

</plugin>

</plugins>

</configuration>


public class Configuration {

protected final InterceptorChain interceptorChain = new InterceptorChain();

}

org.apache.ibatis.plugin.InterceptorChain.java源码:

public class InterceptorChain {

private final List interceptors = new ArrayList();

public Object pluginAll(Object target) {

for (Interceptor interceptor : interceptors) {

target = interceptor.plugin(target);

}

return target;

}

public void addInterceptor(Interceptor interceptor) {

interceptors.add(interceptor);

}

public List getInterceptors() {

return Collections.unmodifiableList(interceptors);

}

}

插件编写

我们自己写的插件必须要实现mybatis的org.apache.ibatis.plugin.Interceptor接口:

public interface Interceptor {

Object intercept(Invocation invocation) throws Throwable;

Object plugin(Object target);

void setProperties(Properties properties);

}

intercept()方法:执行拦截内容的地方,比如想收点保护费。由plugin()方法触发,interceptor.plugin(target)足以证明。

plugin()方法:决定是否触发intercept()方法。

setProperties()方法:给自定义的拦截器传递xml配置的属性参数。

自定义一个拦截器:

@Intercepts({

@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,

RowBounds.class, ResultHandler.class }),

@Signature(type = Executor.class, method = "close", args = { boolean.class }) })

public class MyBatisInterceptor implements Interceptor {

private Integer value;

@Override

public Object intercept(Invocation invocation) throws Throwable {

// 从 Invocation 中获取参数 final Object[] queryArgs = invocation.getArgs();

        final MappedStatement ms = (MappedStatement) queryArgs[MAPPEDSTATEMENT_INDEX];

        final Object parameter = queryArgs[PARAMETER_INDEX];

        //  获取分页参数        Page paingParam = PageUtil.getPaingParam();

        if (paingParam != null) {

            // 构造新的 sql, select xxx from xxx where yyy limit offset,limit            final BoundSql boundSql = ms.getBoundSql(parameter);

            String pagingSql = getPagingSql(boundSql.getSql(), paingParam.getOffset(), paingParam.getLimit());

            // 设置新的 MappedStatement            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), pagingSql,

                    boundSql.getParameterMappings(), boundSql.getParameterObject());

            MappedStatement mappedStatement = newMappedStatement(ms, newBoundSql);

            queryArgs[MAPPEDSTATEMENT_INDEX] = mappedStatement;

            // 重置 RowBound            queryArgs[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);

        }

        Object result = invocation.proceed();

        PageUtil.removePagingParam();

        return result;

}

@Override

public Object plugin(Object target) {

System.out.println(value);

// Plugin类是插件的核心类,用于给target创建一个JDK的动态代理对象,触发intercept()方法

return Plugin.wrap(target, this);

}

@Override

public void setProperties(Properties properties) {

value = Integer.valueOf((String) properties.get("value"));

}

}

注解的作用:

@Intercepts注解:装载一个@Signature列表,一个@Signature其实就是一个需要拦截的方法封装。那么,一个拦截器要拦截多个方法,自然就是一个@Signature列表。

type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }

解释:要拦截Executor接口内的query()方法,参数类型为args列表。

如何执行这个插件呢?

请看自定义代码中的Plugin.wrap(target, this),这是用JDK的动态代理机制来实现的,以此来实现方法的拦截和增强功能,执行后会回调intercept()方法。

org.apache.ibatis.plugin.Plugin.java源码:

public class Plugin implements InvocationHandler {

private Object target;

private Interceptor interceptor;

private Map, Set> signatureMap;

private Plugin(Object target, Interceptor interceptor, Map, Set> signatureMap) {

this.target = target;

this.interceptor = interceptor;

this.signatureMap = signatureMap;

}

public static Object wrap(Object target, Interceptor interceptor) {

Map, Set> signatureMap = getSignatureMap(interceptor);

Class type = target.getClass();

Class[] interfaces = getAllInterfaces(type, signatureMap);

if (interfaces.length > 0) {

// 创建JDK动态代理对象

return 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 methods = signatureMap.get(method.getDeclaringClass());

// 判断是否是需要拦截的方法(很重要)

if (methods != null && methods.contains(method)) {

// 回调intercept()方法

return interceptor.intercept(new Invocation(target, method, args));

}

return method.invoke(target, args);

} catch (Exception e) {

throw ExceptionUtil.unwrapThrowable(e);

}

}

//...

}

Map<Class<?>, Set<Method>> signatureMap:缓存需拦截对象的反射结果,避免多次反射,即target的反射结果。

mybatis可以拦截哪些对象呢?

请看mybatis的Configuration构造类

public class Configuration {

//...

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {

ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);

parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); // 1

return parameterHandler;

}

public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,

ResultHandler resultHandler, BoundSql boundSql) {

ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);

resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler); // 2

return resultSetHandler;

}

public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);

statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); // 3

return statementHandler;

}

public Executor newExecutor(Transaction transaction) {

return newExecutor(transaction, defaultExecutorType);

}

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {

executorType = executorType == null ? defaultExecutorType : executorType;

executorType = executorType == null ? ExecutorType.SIMPLE : executorType;

Executor executor;

if (ExecutorType.BATCH == executorType) {

executor = new BatchExecutor(this, transaction);

} else if (ExecutorType.REUSE == executorType) {

executor = new ReuseExecutor(this, transaction);

} else {

executor = new SimpleExecutor(this, transaction);

}

if (cacheEnabled) {

executor = new CachingExecutor(executor);

}

executor = (Executor) interceptorChain.pluginAll(executor); // 4

return executor;

}

//...

}

mybatis只能拦截ParameterHandler、ResultSetHandler、StatementHandler、Executor共4个接口对象内的方法。

interceptorChain.pluginAll():该方法在创建上述4个接口对象时调用,其含义为给这些接口对象注册拦截器功能,注意是注册,而不是执行拦截。

拦截器执行时机:plugin()方法注册拦截器后,那么,在执行上述4个接口对象内的具体方法时,就会自动触发拦截器的执行,也就是插件的执行。

Invocation

调用执行拦截

public class Invocation {

private Object target;

private Method method;

private Object[] args;

}

org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XNode)方法部分源码:

pluginElement(root.evalNode("plugins"));

private void pluginElement(XNode parent) throws Exception {

if (parent != null) {

for (XNode child : parent.getChildren()) {

String interceptor = child.getStringAttribute("interceptor");

Properties properties = child.getChildrenAsProperties();

Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();

// 这里展示了setProperties()方法的调用时机

interceptorInstance.setProperties(properties);

configuration.addInterceptor(interceptorInstance);

}

}

}

可以看到,上面并没有明确标明哪种拦截器,统一获取的是plugins的配置,即所有拦截器。因此对于Mybatis,它并不区分是何种拦截器接口,所有的插件都是Interceptor,Mybatis完全依靠Annotation去标识对谁进行拦截,所以,具备接口一致性。

分页插件原理

我们通常用mybatis开发,都是手写sql,通过逻辑进行分页,那么不希望通过逻辑分页,传入sql直接分页,物理强行进行分页可否?这里就用到插件功能了。

要实现物理分页,就需要对String sql进行拦截并增强,Mybatis通过BoundSql对象存储String sql,而BoundSql则由StatementHandler对象获取。

public interface StatementHandler {

List query(Statement statement, ResultHandler resultHandler) throws SQLException;

BoundSql getBoundSql();

}

public class BoundSql {

public String getSql() {

return sql;

}

}

因此,就需要编写一个针对StatementHandler的query方法拦截器,然后获取到sql,对sql进行重写增强。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354