分享

MyBATIS中的插件原理和应用

 昵称20874412 2017-09-19

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


1、插件接口:

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

[java] view plain copy
  1. package org.apache.ibatis.plugin;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. public interface Interceptor {  
  6.   
  7.     public Object intercept(Invocation invctn) throws Throwable;  
  8.   
  9.     public Object plugin(Object o);  
  10.   
  11.     public void setProperties(Properties prprts);  
  12. }  

好,它有三个方法:

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

2、插件初始化

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

[java] view plain copy
  1. private void pluginElement(XNode parent) throws Exception {  
  2.   if (parent != null) {  
  3.     for (XNode child : parent.getChildren()) {  
  4.       String interceptor = child.getStringAttribute("interceptor");  
  5.       Properties properties = child.getChildrenAsProperties();  
  6.       Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();  
  7.       interceptorInstance.setProperties(properties);  
  8.       configuration.addInterceptor(interceptorInstance);  
  9.     }  
  10.   }  
  11. }  

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


3、插件的取出:

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

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

[java] view plain copy
  1. public Executor newExecutor(Transaction transaction, ExecutorType executorType) {  
  2.     executorType = executorType == null ? defaultExecutorType : executorType;  
  3.     executorType = executorType == null ? ExecutorType.SIMPLE : executorType;  
  4.     Executor executor;  
  5.     if (ExecutorType.BATCH == executorType) {  
  6.       executor = new BatchExecutor(this, transaction);  
  7.     } else if (ExecutorType.REUSE == executorType) {  
  8.       executor = new ReuseExecutor(this, transaction);  
  9.     } else {  
  10.       executor = new SimpleExecutor(this, transaction);  
  11.     }  
  12.     if (cacheEnabled) {  
  13.       executor = new CachingExecutor(executor);  
  14.     }  
  15.     executor = (Executor) interceptorChain.pluginAll(executor);  
  16.     return executor;  
  17.   }  

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

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

[java] view plain copy
  1. private final List<Interceptor> interceptors = new ArrayList<Interceptor>();  
  2.   
  3.   public Object pluginAll(Object target) {  
  4.     for (Interceptor interceptor : interceptors) {  
  5.       target = interceptor.plugin(target);  
  6.     }  
  7.     return target;  
  8.   }  

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

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


4、插件的运行原理

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

[java] view plain copy
  1. package org.apache.ibatis.plugin;  
  2.   
  3. import java.lang.reflect.InvocationHandler;  
  4. import java.lang.reflect.Method;  
  5. import java.lang.reflect.Proxy;  
  6. import java.util.HashMap;  
  7. import java.util.HashSet;  
  8. import java.util.Map;  
  9. import java.util.Set;  
  10.   
  11. import org.apache.ibatis.reflection.ExceptionUtil;  
  12. public class Plugin implements InvocationHandler {  
  13.   
  14.   private Object target;  
  15.   private Interceptor interceptor;  
  16.   private Map<Class<?>, Set<Method>> signatureMap;  
  17.   
  18.   private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {  
  19.     this.target = target;  
  20.     this.interceptor = interceptor;  
  21.     this.signatureMap = signatureMap;  
  22.   }  
  23.   
  24.   public static Object wrap(Object target, Interceptor interceptor) {  
  25.     Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);  
  26.     Class<?> type = target.getClass();  
  27.     Class<?>[] interfaces = getAllInterfaces(type, signatureMap);  
  28.     if (interfaces.length > 0) {  
  29.       return Proxy.newProxyInstance(  
  30.           type.getClassLoader(),  
  31.           interfaces,  
  32.           new Plugin(target, interceptor, signatureMap));  
  33.     }  
  34.     return target;  
  35.   }  
  36.   
  37.   @Override  
  38.   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  39.     try {  
  40.       Set<Method> methods = signatureMap.get(method.getDeclaringClass());  
  41.       if (methods != null && methods.contains(method)) {  
  42.         return interceptor.intercept(new Invocation(target, method, args));  
  43.       }  
  44.       return method.invoke(target, args);  
  45.     } catch (Exception e) {  
  46.       throw ExceptionUtil.unwrapThrowable(e);  
  47.     }  
  48.   }  
  49.   
  50.   private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {  
  51.     Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);  
  52.     // issue #251  
  53.     if (interceptsAnnotation == null) {  
  54.       throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());        
  55.     }  
  56.     Signature[] sigs = interceptsAnnotation.value();  
  57.     Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();  
  58.     for (Signature sig : sigs) {  
  59.       Set<Method> methods = signatureMap.get(sig.type());  
  60.       if (methods == null) {  
  61.         methods = new HashSet<Method>();  
  62.         signatureMap.put(sig.type(), methods);  
  63.       }  
  64.       try {  
  65.         Method method = sig.type().getMethod(sig.method(), sig.args());  
  66.         methods.add(method);  
  67.       } catch (NoSuchMethodException e) {  
  68.         throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);  
  69.       }  
  70.     }  
  71.     return signatureMap;  
  72.   }  
  73.   
  74.   private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {  
  75.     Set<Class<?>> interfaces = new HashSet<Class<?>>();  
  76.     while (type != null) {  
  77.       for (Class<?> c : type.getInterfaces()) {  
  78.         if (signatureMap.containsKey(c)) {  
  79.           interfaces.add(c);  
  80.         }  
  81.       }  
  82.       type = type.getSuperclass();  
  83.     }  
  84.     return interfaces.toArray(new Class<?>[interfaces.size()]);  
  85.   }  
  86.   
  87. }  

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

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

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

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

[java] view plain copy
  1. public class Invocation {  
  2.   
  3.   private Object target;  
  4.   private Method method;  
  5.   private Object[] args;  
  6.   
  7.   public Invocation(Object target, Method method, Object[] args) {  
  8.     this.target = target;  
  9.     this.method = method;  
  10.     this.args = args;  
  11.   }  
  12.   
  13.   public Object getTarget() {  
  14.     return target;  
  15.   }  
  16.   
  17.   public Method getMethod() {  
  18.     return method;  
  19.   }  
  20.   
  21.   public Object[] getArgs() {  
  22.     return args;  
  23.   }  
  24.   
  25.   public Object proceed() throws InvocationTargetException, IllegalAccessException {  
  26.     return method.invoke(target, args);  
  27.   }  
  28.   
  29. }  

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

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



5、插件的开发:

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

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

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

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

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


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

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

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

我们在看到接口StatementHandler:

[java] view plain copy
  1. package org.apache.ibatis.executor.statement;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5. import java.sql.Statement;  
  6. import java.util.List;  
  7. import org.apache.ibatis.executor.parameter.ParameterHandler;  
  8. import org.apache.ibatis.mapping.BoundSql;  
  9. import org.apache.ibatis.session.ResultHandler;  
  10.   
  11. public interface StatementHandler {  
  12.   
  13.     public Statement prepare(Connection cnctn) throws SQLException;  
  14.   
  15.     public void parameterize(Statement stmnt) throws SQLException;  
  16.   
  17.     public void batch(Statement stmnt) throws SQLException;  
  18.   
  19.     public int update(Statement stmnt) throws SQLException;  
  20.   
  21.     public <E extends Object> List<E> query(Statement stmnt, ResultHandler rh) throws SQLException;  
  22.   
  23.     public BoundSql getBoundSql();  
  24.   
  25.     public ParameterHandler getParameterHandler();  
  26. }  
我们清楚的可以看到prepare方法里面有一个参数Connection,所以就很简单的得到下面的签名注册: 

[java] view plain copy
  1. @Intercepts({  
  2. @Signature(type = StatementHandler.class,  
  3. method = "prepare",  
  4. args = {Connection.class})})  
  5. public class PagingInterceptor implements Interceptor {  
  6.   
  7. ......  
  8. }  
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());

这只是一个工具类。


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

[java] view plain copy
  1. package com.ykzhen.charter3.plugin;  
  2.   
  3. import java.sql.Connection;  
  4. import java.util.Properties;  
  5. import org.apache.ibatis.executor.statement.StatementHandler;  
  6. import org.apache.ibatis.mapping.BoundSql;  
  7. import org.apache.ibatis.plugin.Interceptor;  
  8. import org.apache.ibatis.plugin.Intercepts;  
  9. import org.apache.ibatis.plugin.Invocation;  
  10. import org.apache.ibatis.plugin.Plugin;  
  11. import org.apache.ibatis.plugin.Signature;  
  12. import org.apache.ibatis.reflection.MetaObject;  
  13. import org.apache.ibatis.reflection.SystemMetaObject;  
  14.   
  15. /** 
  16.  * 
  17.  * @author ykzhen. 
  18.  */  
  19. @Intercepts({  
  20.     @Signature(type = StatementHandler.class,  
  21.             method = "prepare",  
  22.             args = {Connection.class})})  
  23. public class PagingInterceptor implements Interceptor {  
  24.   
  25.     private int limit = 0;  
  26.       
  27.     @Override  
  28.     public Object intercept(Invocation invocation) throws Throwable {  
  29.         StatementHandler statementHandler = (StatementHandler) invocation.getTarget();  
  30.         MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);  
  31.         // 分离代理对象链(由于目标类可能被多个拦截器拦截,从而形成多次代理,通过循环可以分离出最原始的的目标类)    
  32.         while (metaStatementHandler.hasGetter("h")) {  
  33.             Object object = metaStatementHandler.getValue("h");  
  34.             metaStatementHandler = SystemMetaObject.forObject(object);  
  35.         }  
  36.           
  37.         //BoundSql对象是处理sql语句的。  
  38.         String sql = (String)metaStatementHandler.getValue("delegate.boundSql.sql");  
  39.         //判断sql是否select语句,如果不是select语句那么就出错了。  
  40.         //如果是修改它,是的它最多返回行,这里用的是mysql,其他数据库要改写成其他  
  41.         if (sql != null && sql.toLowerCase().trim().indexOf("select") == 0 && !sql.contains("$_$limit_$table_")) {  
  42.             //通过sql重写来实现,这里我们起了一个奇怪的别名,避免表名重复.  
  43.             sql = "select * from (" + sql + ") $_$limit_$table_ limit " + this.limit;  
  44.             metaStatementHandler.setValue("delegate.boundSql.sql", sql); //重写SQL  
  45.         }  
  46.         return invocation.proceed();//实际就是调用原来的prepared方法,只是再次之前我们修改了sql  
  47.     }  
  48.   
  49.     @Override  
  50.     public Object plugin(Object target) {  
  51.         return Plugin.wrap(target, this);//使用Plugin的wrap方法生成代理对象  
  52.     }  
  53.   
  54.     @Override  
  55.     public void setProperties(Properties props) {  
  56.         String limitStr = props.get("page.limit").toString();  
  57.         this.limit = Integer.parseInt(limitStr);//用传递进来的参数初始化  
  58.     }  
  59.   
  60. }  

4、配置插件

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

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


好运行一下,完全成功。


[plain] view plain copy
  1. DEBUG 2015-12-18 10:42:16,758 org.apache.ibatis.logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.  
  2.   DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.  
  3.   DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.  
  4.   DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.  
  5.   DEBUG 2015-12-18 10:42:16,769 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.  
  6.   DEBUG 2015-12-18 10:42:16,918 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection  
  7.   DEBUG 2015-12-18 10:42:17,168 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 1897871865.  
  8.   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]  
  9.   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   
  10.   DEBUG 2015-12-18 10:42:17,194 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters:   
  11.    INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串  
  12.    INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串  
  13.    INFO 2015-12-18 10:42:17,241 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串  
  14.    INFO 2015-12-18 10:42:17,242 com.ykzhen.charter3.typeHandler.MyStringTypeHandler: 使用我的TypeHandler,ResultSet列名获取字符串  
  15.   DEBUG 2015-12-18 10:42:17,242 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 4  
  16. [com.ykzhen.charter3.pojo.Role@4232c52b, com.ykzhen.charter3.pojo.Role@1877ab81, com.ykzhen.charter3.pojo.Role@305fd85d, com.ykzhen.charter3.pojo.Role@458c1321]  
  17.   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]  
  18.   DEBUG 2015-12-18 10:42:17,256 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@711f39f9]  
  19.   DEBUG 2015-12-18 10:42:17,256 org.apache.ibatis.datasource.pooled.PooledDataSource: Returned connection 1897871865 to pool.  

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多