Mybaits简单的插件写法

 

Mybatis插件的书写流程:

1.编写Interceptor接口的实现类
2.使用@Intercepts注解完成插件签名(拦截那个类的那个方法)

@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
//那个类(四大对象),的哪个方法及方法形参类型

3.将写好的插件注册到全局配置文件中(mybatis-config.xml)

<plugins>
    <plugin interceptor="全类名" >
        <property name="username" value="root" />
    </plugin>
</plugins>

 

 

支持拦截的方法

  • 执行器Executor(update、query、commit、rollback等方法);
  • 参数处理器ParameterHandler(getParameterObject、setParameters方法);
  • 结果集处理器ResultSetHandler(handleResultSets、handleOutputParameters等方法);
  • SQL语法构建器StatementHandler(prepare、parameterize、batch、update、query等方法);


下面是一个简单的插件:

功能:拦截ParameterHandler的setParameters,目的是在处理查询sql参数时,改变一下原来的where条件参数. 

比如:select * from t_user where id=1, 永久把id=1改为3,就是说不管页面传的id值是多少,一直查询id=3的数据

 

package com.cc8w.plugin;


import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Statement;
import java.util.Properties;

/**
 * 练习mybatis插件,熟悉其原理
 *
 * 一.mybatis插件实现步骤
 * 1.编写Interceptor接口的实现类
 * 2.使用@Intercepts注解完成插件签名(拦截那个类的那个方法)
 * 3.将写好的插件注册到全局配置文件中(mybatis-config.xml)
 *
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "parameterize", args = {java.sql.Statement.class})
})
public class MybaitsPlugin implements Interceptor {


    /**
     * intercept 拦截目标对象的目标方法执行;
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //需求:获取查询参数,更改查询参数为id=3

        Object target = invocation.getTarget();//当前拦截到的目标对象
        //1.拿到StatementHandler==>ParameterHandler==>parameterObject
        MetaObject metaObjetc = SystemMetaObject.forObject(target); //可以拿到目标对象的元数据
        //2.操作MetaObject可以很方便的得到目标对象的所有值
        Object value = metaObjetc.getValue("parameterHandler.parameterObject");//获取那个属性的值(注意大小写)
        System.out.println("sql语句用的参数是:"+value);
        //3.根据需求把这个值改为3,即可
        metaObjetc.setValue("parameterHandler.parameterObject",3);//设置那个属性的值


        Object proceed = invocation.proceed();//放行语句,执行目标方法
        return proceed;
    }

    /**
     * 包装目标对象:为目标对象创建一个代理对象
     *
     * @param target
     * @return
     */
    @Override
    public Object plugin(Object target) {
        //借助Plugin类的wrap方法,来使用当前Interceptor包装我们的目标对象
        Object wrap = Plugin.wrap(target,this);
        //返回当前target创建的动态代理
        return wrap;
    }

    /**
     * 注册时:设置一些配置参数
     *
     * @param properties
     */
    @Override
    public void setProperties(Properties properties) {

    }
}

 

 

mybatis-config.xml中配置

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
        <plugin interceptor="com.cc8w.plugin.MybaitsPlugin"></plugin>
    </plugins>

 

 

 

例子2: Executor拦截器

@Intercepts({
        // @Signature(type = Executor.class, method = /* org.apache.ibatis.executor.Executor中定义的方法,参数也要对应 */"update", args = { MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,RowBounds.class, ResultHandler.class }) })
public class SelectPruningColumnPlugin implements Interceptor {
    public static final ThreadLocal<ColumnPruning> enablePruning = new ThreadLocal<ColumnPruning>(){
        @Override
        protected ColumnPruning initialValue()
        {
            return null;
        }
    };
    
    Logger logger = LoggerFactory.getLogger(SelectPruningColumnPlugin.class);
    
    static int MAPPED_STATEMENT_INDEX = 0;// 这是对应上面的args的序号
    static int PARAMETER_INDEX = 1;
    static int ROWBOUNDS_INDEX = 2;
    static int RESULT_HANDLER_INDEX = 3;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (enablePruning.get() != null && enablePruning.get().isEnablePruning()) {
            Object[] queryArgs = invocation.getArgs();
            MappedStatement mappedStatement = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
            Object parameter = queryArgs[PARAMETER_INDEX];
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            String sql = boundSql.getSql();// 获取到SQL ,进行调整
            String name = mappedStatement.getId();
            logger.debug("拦截的方法名是:" + name + ",sql是" + sql + ",参数是" + JsonUtils.toJson(parameter));
            String execSql = pruningColumn(enablePruning.get().getReserveColumns(), sql);
            logger.debug("修改后的sql是:" + execSql);

            // 重新new一个查询语句对像
            BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), execSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
            // 把新的查询放到statement里
            MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
            for (ParameterMapping mapping : boundSql.getParameterMappings()) {
                String prop = mapping.getProperty();
                if (boundSql.hasAdditionalParameter(prop)) {
                    newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
                }
            }
            queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
            // 因为涉及分页查询PageHelper插件,所以不能设置为null,需要业务上下文执行完成后设置为null
//            enablePruning.set(null);
        }
        Object result = invocation.proceed();
        return result;
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
    }

 

例子三: ResultSetHandler拦截器

@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class}) })
public class OptMapPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        Statement stmt = (Statement) invocation.getArgs()[0];
        if (target instanceof DefaultResultSetHandler) {
            DefaultResultSetHandler resultSetHandler = (DefaultResultSetHandler) target;
            Class clz = resultSetHandler.getMappedStatement().getResultMaps().get(0).getType();
            if (clz == OptMap.class) {
                List<Object> resultList = new ArrayList<Object>();
                OptMap optMap = new OptMap();
                resultList.add(optMap);
                resultSet2OptMap(resultSetHandler.getConfiguration(),resultSetHandler,optMap,stmt.getResultSet());
                return resultList;
            }
            return invocation.proceed();
        }
        //如果没有进行拦截处理,则执行默认逻辑
        return invocation.proceed();
    }

 

转 :  https://www.cnblogs.com/zhjh256/p/11516878.html

 

posted @ 2020-08-21 00:21  与f  阅读(406)  评论(0编辑  收藏  举报