MyBATIS中的插件原理和应用

18 篇文章 8 订阅

如果你不懂反射和动态代理请参考我的博文:http://blog.csdn.net/ykzhen2015/article/details/50312651
这是本文的基础,请先掌握它,否则下面内容的将寸步难行。


1、插件接口:

首先在mybatis中要使用插件你必须实现:org.apache.ibatis.plugin.Interceptor接口,我们先看看它的定义。

package org.apache.ibatis.plugin;

import java.util.Properties;

public interface Interceptor {

    public Object intercept(Invocation invctn) throws Throwable;

    public Object plugin(Object o);

    public void setProperties(Properties prprts);
}

好,它有三个方法:

    intercept 真个是插件真正运行的方法,它将直接覆盖掉你真实拦截对象的方法。里面有一个Invocation对象,利用它可以调用你原本要拦截的对象的方法
    plugin    它是一个生成动态代理对象的方法,
    setProperties 它是允许你在使用插件的时候设置参数值。

2、插件初始化

MyBATIS是在初始化上下文环境的时候就初始化插件的,我们看到源码:

  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();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

这里我们看到它生成了interceptor的实例,然后调度了setProperties方法,设置你配置的参数。跟着就是保存在Configuration对象里面。感兴趣的朋友可以往下看源码,它最后是把所有的插件按你配置的顺序保存在一个list对象里面。这里就不累赘了。


3、插件的取出:

MyBATIS的插件可以拦截Executor,StatementHandler,ParameterHandler和ResultHandler对象(下简称四大对象)

其实在取出四大对象的时候,方法是接近的,这里让我们看看Executor对象的取出:

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);
    return executor;
  }

这个方法还是比较简单的,首先根据配置来决定生成什么样的Executor对象(simple,batch和ResuseExector),然后就执行了这么一句话:

executor = (Executor) interceptorChain.pluginAll(executor);
这样我们对pluginAll方法很感兴趣,我们再看看它的源码:

private final List<Interceptor> interceptors = new ArrayList<Interceptor>();

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

这里我们清楚它从我们配置的插件里面取出插件,然后用插件的plugin方法去生成代理对象(文章开始已经告诉读者plugin方法的意义)。现在假设我有n个插件

拦截executor,那么第一次调用plugin的时候,就会生成代理对象proxy1,第二次调用传递的是proxy1,就会生成代理对象proxy2.....直到最后第n此调用生成proxyn。我们知道当生成代理对象的时候就会进入绑定的invoke方法里。


4、插件的运行原理

为了方便生成代理对象和绑定方法,MyBATIS为我们提供了一个Plugin类的,我们经常需要在插件的plugin方法中调用它,让我们看看它:

package org.apache.ibatis.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.reflection.ExceptionUtil;
public class Plugin implements InvocationHandler {

  private Object target;
  private Interceptor interceptor;
  private Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  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 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);
    }
  }

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
      if (methods == null) {
        methods = new HashSet<Method>();
        signatureMap.put(sig.type(), methods);
      }
      try {
        Method method = sig.type().getMethod(sig.method(), sig.args());
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }

  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }

}

这里有两个十分重要的方法,wrap和invoke方法。

wrap方法显然是为了生成一个动态代理类。它利用接口Interceptor绑定,用Plugin类对象代理,这样被绑定对象调用方法时,就会进入Plugin类的invoke方法里。

invoke方法是代理绑定的方法。学习了动态代理就知道,当一个对象被wrap方法绑定就会进入到这个方法里面。

invoke方法实现的逻辑是:首先判定签名类和方法是否存在,如果不存在则直接反射调度被拦截对象的方法,如果存在则调度插件的interceptor方法,这时候会初始化一个Invocation对象,这个对象比较简单,我们来看看它:

public class Invocation {

  private Object target;
  private Method method;
  private Object[] args;

  public Invocation(Object target, Method method, Object[] args) {
    this.target = target;
    this.method = method;
    this.args = args;
  }

  public Object getTarget() {
    return target;
  }

  public Method getMethod() {
    return method;
  }

  public Object[] getArgs() {
    return args;
  }

  public Object proceed() throws InvocationTargetException, IllegalAccessException {
    return method.invoke(target, args);
  }

}

这里方法都比较简单,我们值得注意的只有proceed方法,它就是直接反射调度被拦截对象的方法。

然后就去执行插件的intercept方法,在MyBATIS插件就是这样运行的。



5、插件的开发:

我们这里做个例子,我需要限制每个查询至多返回100条记录,而这数字100是一个可配置的参数。

1、确定拦截什么对象,什么方法。

从上面的原来来看,我们首先需要确定插件拦截什么对象的什么方法

这个需要了解sqlSession的执行原理,你可以参考我的文章:

MyBatis原理第四篇——statementHandler对象(sqlSession内部核心实现,插件的基础)


从文中读者可以知道执行查询是使用StatementHandler的prepare预编译SQL,使用parameterize设置参数,使用query执行查询。

我们希望的是在预编译前去修改sql,做出加入limit语句限制sql的返回。(这里我用的是Mysql,如果用其他数据库需要自己编写你自己的sql),因此我们要拦截prepare方法。

2、我们需要提供签名信息.

我们在看到接口StatementHandler:

package org.apache.ibatis.executor.statement;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.ResultHandler;

public interface StatementHandler {

    public Statement prepare(Connection cnctn) throws SQLException;

    public void parameterize(Statement stmnt) throws SQLException;

    public void batch(Statement stmnt) throws SQLException;

    public int update(Statement stmnt) throws SQLException;

    public <E extends Object> List<E> query(Statement stmnt, ResultHandler rh) throws SQLException;

    public BoundSql getBoundSql();

    public ParameterHandler getParameterHandler();
}
我们清楚的可以看到prepare方法里面有一个参数Connection,所以就很简单的得到下面的签名注册:

@Intercepts({
@Signature(type = StatementHandler.class,
method = "prepare",
args = {Connection.class})})
public class PagingInterceptor implements Interceptor {

......
}

type告诉要拦截什么对象,它可以是四大对象的一个。

method告诉你要拦截什么方法。

args告诉方法的参数是什么。


3、实现拦截器:

在实现前我们需要熟悉一个mybatis中常用的类的使用。它便是:MetaObject

它的作用是可以帮助我们取到一些属性和设置属性(包括私有的)。它有三个方法:

MetaObject forObject(Object object,ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory)

这个方法我们基本不用了,因为MyBATIS中可以用SystemMetaObject.forObject(Object obj)代替它。

Object getValue(String name)

void setValue(String name, Object value)

第一个方法是绑定对象,第二个方法是根据路径获取值,第三个方法是获取值。

这些说还是有点抽象,我们举个例子,比如说现在我有个学生对象(student),它下面有个属性学生证(selfcard),学生证也有个属性发证日期(date)。

但是发证日期是一个私有的属性且没有提供公共方法访问。我们现在需要访问它,那么我们就可以使用MetaObject将其绑定:

MetaObject metaStudent = SystemMetaObject.forObject(student);

这样便可以读取它的属性:

Date date =(Date) metaStudent.getValue("selfcard.date");

或者设置它的属性:

metaStudent.setValue("selfcard.date", new Date());

这只是一个工具类。


现在我们来实现这个插件:

package com.ykzhen.charter3.plugin;

import java.sql.Connection;
import java.util.Properties;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

/**
 *
 * @author ykzhen.
 */
@Intercepts({
    @Signature(type = StatementHandler.class,
            method = "prepare",
            args = {Connection.class})})
public class PagingInterceptor implements Interceptor {

    private int limit = 0;
    
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        // 分离代理对象链(由于目标类可能被多个拦截器拦截,从而形成多次代理,通过循环可以分离出最原始的的目标类)  
        while (metaStatementHandler.hasGetter("h")) {
            Object object = metaStatementHandler.getValue("h");
            metaStatementHandler = SystemMetaObject.forObject(object);
        }
        
        //BoundSql对象是处理sql语句的。
        String sql = (String)metaStatementHandler.getValue("delegate.boundSql.sql");
        //判断sql是否select语句,如果不是select语句那么就出错了。
        //如果是修改它,是的它最多返回行,这里用的是mysql,其他数据库要改写成其他
        if (sql != null && sql.toLowerCase().trim().indexOf("select") == 0 && !sql.contains("$_$limit_$table_")) {
            //通过sql重写来实现,这里我们起了一个奇怪的别名,避免表名重复.
            sql = "select * from (" + sql + ") $_$limit_$table_ limit " + this.limit;
            metaStatementHandler.setValue("delegate.boundSql.sql", sql); //重写SQL
        }
        return invocation.proceed();//实际就是调用原来的prepared方法,只是再次之前我们修改了sql
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);//使用Plugin的wrap方法生成代理对象
    }

    @Override
    public void setProperties(Properties props) {
        String limitStr = props.get("page.limit").toString();
        this.limit = Integer.parseInt(limitStr);//用传递进来的参数初始化
    }

}

4、配置插件

好最后我们来配置这个插件:

<plugins>
        <plugin interceptor="com.ykzhen.charter3.plugin.PagingInterceptor">
            <property name="page.limit" value="100"/>
        </plugin>
    </plugins>
这里的page.limit属性是可以配置的,我们当前配置为100。我们知道它在插件的setProperties方法中被调用。可以根据你的需要配置。


好运行一下,完全成功。


DEBUG 2015-12-18 10:42:16,758 org.apache.ibatis.logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
  DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
  DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
  DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
  DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
  DEBUG 2015-12-18 10:42:16,918 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
  DEBUG 2015-12-18 10:42:17,168 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 1897871865.
  DEBUG 2015-12-18 10:42:17,168 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@711f39f9]
  DEBUG 2015-12-18 10:42:17,175 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from (select role_no, role_name, note from t_role) $_$limit_$table_ limit 100 
  DEBUG 2015-12-18 10:42:17,194 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 
   INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串
   INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串
   INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串
   INFO 2015-12-18 10:42:17,242 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串
  DEBUG 2015-12-18 10:42:17,242 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 4
[com.ykzhen.charter3.pojo.Role@4232c52b, com.ykzhen.charter3.pojo.Role@1877ab81, com.ykzhen.charter3.pojo.Role@305fd85d, com.ykzhen.charter3.pojo.Role@458c1321]
  DEBUG 2015-12-18 10:42:17,251 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@711f39f9]
  DEBUG 2015-12-18 10:42:17,256 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@711f39f9]
  DEBUG 2015-12-18 10:42:17,256 org.apache.ibatis.datasource.pooled.PooledDataSource: Returned connection 1897871865 to pool.

从日志可以看到它加入了我们重写SQL的逻辑,完全成功了。





.

  • 24
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值