ibatis sql 拦截器 插件 实现 demo

2018-01-14

138

0

技术:ibatis3.2.3 + java8

运行环境:IDEA 15.2 + jdk8 + windows10

demo功能:提供一个ibatis3.2.3 拦截器 demo

拦截器代码-记录sql执行的时间

package com.demoworld.interceptor;

/**
 * Created by francis on 2018/1/14.
 */

import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

@Intercepts(value = {
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})})
public class SqlStatementInterceptor implements Interceptor {
    private Properties properties;

    @Override
    public Object intercept(Invocation arg0) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) arg0.getArgs()[0];//注意arg0.getArgs()数组中每个参数的含义
        String sqlId = mappedStatement.getId();
        Object returnValue;

        long start = System.currentTimeMillis();
        returnValue = arg0.proceed();
        long end = System.currentTimeMillis();
        long time = end - start;

        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(": ");
        str.append("cost time ");
        str.append(time);
        str.append(" ms.");
        String sqlInfo = str.toString();
        System.out.println(sqlInfo);
        return returnValue;
    }

    @Override
    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }

    @Override
    public void setProperties(Properties arg0) {
        this.properties = arg0;
    }
}

 

xml配置拦截器, 注意节点在configuration节点中的位置

 

步骤3

步骤4

xxxxxxxxxxxxxxxxxxxxxxx

步骤5

xxxxxxxxxxxxxxxxxxxxxxx

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think