Mybatis如何优雅打印SQL

Mybatis如何优雅打印SQL

正常情况下,程序中使用到的sql,参数都是以逗号的形式作为替换符,参数均在下一行打印,参数太多时,我们排查需要将参数一个一个的复制,并填充问号,使用起来很不方便

新的改变

我们可以自己写一个插件,在mybatis执行时将程序中使用到的sql、参数等信息提取出来,再将其拼接打印:

  1. 自定义插件
package com.dhcc.dqc.configuration;

import lombok.extern.slf4j.Slf4j;
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.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.util.ObjectUtils;

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

/**
 * author:zyk
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.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 = "update", args = {MappedStatement.class,Object.class}),
})
@Slf4j
public class SqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object proceed = invocation.proceed();
        long endTime = System.currentTimeMillis();

        String printSql = null;
        try {
            //通过generateSql方法拿到最终生成的SQL
            printSql = generateSql(invocation);
        } catch (Exception e) {
            log.error("获取sql异常", e);
        } finally {
            long costTime = endTime - startTime;
            log.info("\n 执行SQL耗时:{}ms \n 执行SQL:{}", costTime, printSql);
        }
        return proceed;
    }

    private String generateSql(Invocation invocation) {
        //获取到BoundSql以及Configuration对象
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }

        // Configuration 对象保存了 Mybatis 架构运行的所有配置信息
        Configuration configuration = statement.getConfiguration();

        // BoundSql 对象存储了一条具体的 SQL 语句以及相关的参数信息
        BoundSql boundSql = statement.getBoundSql(parameter);

        //获取参数信息
        Object parameterObject = boundSql.getParameterObject();
        //获取参数的映射
        List<ParameterMapping> params = boundSql.getParameterMappings();
        //获取到执行的sql
        String sql = boundSql.getSql();
        //多个空格使用一个空格替代
        sql.replaceAll("[\\s]+", " ");

        if (!ObjectUtils.isEmpty(parameterObject) && !ObjectUtils.isEmpty(params)) {
            //TypeHandlerRegistry 是 Mybatis用来管理 TypeHandler 的注册器,TypeHandler 用于在 Java 类型和 JDBC 类型之间进行转换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            //如果参数对象的类型有对应的 TypeHandler ,则使用 TypeHandler 进行处理
            int num=0;
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                //否则,这个处理参数映射关系
                for (ParameterMapping param : params) {
                    //获取参数的属性名
                    String propertyName = param.getProperty();
                    MetaObject metaObject = configuration.newMetaObject(parameterObject);
                    // 检查对象中是否存在该属性的 Getter 方法,如果存在提取出来进行替换
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                        //检查 BoundSql 中是否存在附加的参数,附加参数可能是在动态 SQL 处理中形成的,有的话进行替换
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        //如果都没有,说明 SQL 匹配不上,带上“缺失”方便找问题
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                }
            }
        }
        //删除多余的行
        sql = sql.replaceAll("(?m)^[ \t]*\r?\n", "");
        return sql;
    }

    private static String getParameterValue(Object object) {
        String value ="";
        if(object instanceof String){
            value="'"+object.toString()+"'";
        }else if (object instanceof Date){
            DateFormat format=DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.CHINA);
            value="'"+format.format(object)+"'";
        } else if (!ObjectUtils.isEmpty(object)) {
            value=object.toString();
        }
        return value;
    }

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

    @Override
    public void setProperties(Properties properties) {
    }
}

  1. 在mybatis配置类中将插件进行注入
/**
	 * 自定义 优雅打印 SQL 插件
	 */
	@Bean
	public ConfigurationCustomizer configurationCustomizer(){
		return configuration -> {
			configuration.addInterceptor(new SqlInterceptor());
		};
	}
  1. 重新启动服务

未使用插件之前SQL打印实例
在这里插入图片描述

使用插件之前SQL打印实例
在这里插入图片描述

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值