mybatis输出执行sql并替换?

mybatis输出执行sql并替换?

mybatis.xml允许用户进行自定义插件plugins
插件需要实现Interceptor接口
代码如下:
MyBatisSQLMonitorPlugin.java

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

import java.util.Properties;

@Intercepts({
        @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})})
public class SQLMonitorPlugin implements Interceptor {

    public SQLMonitorPlugin() {
    }

    public Object intercept(Invocation invocation) throws Throwable {
        return MyBatisSQLMonitorPlugin.intercept(invocation);
    }

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

    public void setProperties(Properties properties) {
    }

}

MyBatisSQLMonitorPlugin:

import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;


public class MyBatisSQLMonitorPlugin {
    protected static final Logger LOGGER = LogManager.getLogger(MyBatisSQLMonitorPlugin.class);
    
    public static Object intercept(Invocation invocation) throws
            Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //请求参数
        Object parameter = null;
        if (1 < invocation.getArgs().length) {
            parameter = invocation.getArgs()[1];
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        String sql = boundSql.getSql();
        //执行的sql所在的mapper文件
        String resource = mappedStatement.getResource();
        //执行sql的dao文件的包名+方法名
        String daoMethod = mappedStatement.getId();
        //去除sql文中的换行
        sql = sql.replace("\n", "").replaceAll("\\s+", " ");
        Configuration configuration = mappedStatement.getConfiguration();
        sql = showSql(configuration, boundSql);
        LOGGER.info("[SQLMonitorPlugin]SQL监控:{},执行SQL:{}", daoMethod, sql);
        Object e = invocation.proceed();
        //此处还可以监控sql执行时长还有返回数据的数据量等
        return e;
    }

    // 进行?的替换
    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();  // 获取参数
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  // sql语句中多个空格都用一个空格代替
        if (CollectionUtils.isNotEmpty(parameterMappings) && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换
       // 如果根据parameterObject.getClass()可以找到对应的类型,则替换
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject))); } else { MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作 for (ParameterMapping parameterMapping : parameterMappings) { String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { Object obj = metaObject.getValue(propertyName); sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); } else if (boundSql.hasAdditionalParameter(propertyName)) { Object obj = boundSql.getAdditionalParameter(propertyName); // 该分支是动态sql sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); } else { sql = sql.replaceFirst("\\?", "缺失"); } } } } return sql; } private static String getParameterValue(Object obj) { String value = null; if (obj instanceof String) { value = "'" + obj.toString() + "'"; } else if (obj instanceof Date) { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); value = "'" + formatter.format(obj) + "'"; } else { if (obj != null) { value = obj.toString(); } else { value = ""; } } return value; } }

最后在mybatis.xml最后加入引入插件


        

你可能感兴趣的:(spring,java,mybatis)