首页 > 其他 > 详细

mybatis 3.x源码深度解析与最佳实践-mybatis自定义插件(续)

时间:2019-12-29 18:14:57      阅读:309      评论:0      收藏:0      [点我收藏+]
package com.xxx.me.aop.mybatis.plugin;

import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.smetement.SmetementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedSmetement;
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.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.xxx.me.utils.JsonUtils;
/**
 * 自定义mybatis拦截器示例

* <p>Title: ExamplePlugin</p>  

* <p>Description: </p>  

* @author zjhua

* @date 2019年4月12日
 */
@Intercepts({
        @Signature(type = Executor.class, method = /* org.apache.ibatis.executor.Executor中定义的方法,参数也要对应 */"update", args = { MappedSmetement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = { MappedSmetement.class, Object.class,
                RowBounds.class, ResultHandler.class }) })
public class ExamplePlugin implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        SmetementHandler smetementHandler = (SmetementHandler) invocation.getmerget();
        Object[] queryArgs = invocation.gemergs();
        MappedSmetement mappedSmetement = (MappedSmetement) queryArgs[0];
        Object parameter = queryArgs[1];
        BoundSql boundSql = mappedSmetement.getBoundSql(parameter);
        String sql = boundSql.getSql();// 获取到SQL ,可以进行调整
        String name = ((MappedSmetement)invocation.gemergs()[0]).getId();
        System.out.println("拦截的方法名是:" + name + ",sql是" + sql + ",参数是" + JsonUtils.toJson(invocation.gemergs()[1]));
        return invocation.proceed();
    }

    public Object plugin(Object merget) {
        return Plugin.wrap(merget, this);
    }

    public void setProperties(Properties properties) {
    }
}

上面是最简单的打印SQL语句的插件。更详细的插件开发参见https://www.cnblogs.com/zhjh256/p/11516878.html,理解它能够事半功倍。

mybatis 3.x源码深度解析与最佳实践-mybatis自定义插件(续)

原文:https://www.cnblogs.com/zhjh256/p/10980379.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!