Java手动打印执行过的sql

1. 拦截器

java 复制代码
package com.xxx.platform.common.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.xxx.platform.common.aop.OLAPQuery;
import com.xxx.platform.constant.CommonConstant;
import com.xxx.platform.util.SQLFormatHelper;
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.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Properties;

/**
 * SQL查询统计拦截器。</p>
 *
 * @author xxx
 * @version 1.0
 * @date 2022/10/27 18:21
 */
@Component
@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}),
        }
)
@Slf4j
public class SQLTimerInterceptor implements Interceptor {

    @Value("${spring.profiles.active}")
    private String profile;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        OLAPQuery olap = null;
        try {
            Method method = invocation.getMethod();
            olap = method.getAnnotation(OLAPQuery.class);
            if (!Objects.isNull(olap)) {
                DynamicDataSourceContextHolder.push(CommonConstant.PSS);
            }
            return invocation.proceed();
        } finally {
            if (!Objects.isNull(olap)) {
                DynamicDataSourceContextHolder.clear();
            }

            long duration = System.currentTimeMillis() - startTime;
            SQLFormatHelper.PrintSQL printSQL = SQLFormatHelper.getFormatSQL(invocation);
            String sqlId = printSQL.sqlId;
            String sql = printSQL.formatSQL;
            int ts = "lmp-sy-dev".equals(profile)?1000:3000;
            if (duration >= ts) {
                log.warn("{} execute SQL>=5s: {} ms, \nSQL: {}", sqlId, duration, sql);
            }
        }
    }

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

    @Override
    public void setProperties(Properties properties) {

    }

}

2. 其他工具类

java 复制代码
package com.xxx.platform.util;

import org.apache.commons.collections.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 java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;

/**
 * SQL格式化工具类。</p>
 * 将mybatis预编译SQL转换为带参数SQL。
 *
 * @author xxx
 * @date 2023/02/01 15:54
 */
public final class SQLFormatHelper {


    public static PrintSQL getFormatSQL(Invocation invocation) {
        PrintSQL sql = new PrintSQL();
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        sql.sqlId = sqlId;
        try {
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            Configuration configuration = mappedStatement.getConfiguration();
            String formatSQL = showSql(configuration, boundSql);
            sql.formatSQL = formatSQL;
        } catch (Exception e) {
            e.printStackTrace();
            BoundSql bs = (BoundSql)invocation.getArgs()[5];
            sql.formatSQL = bs.getSql();
        }

        return sql;
    }

    /**
     * 如果参数是String,则添加单引号, 如果是日期,则转换为时间格式器并加单引号;
     * 对参数是null和不是null的情况作了处理
     *
     * @param obj obj
     * @return java.lang.String
     */
    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);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

    /**
     * 进行?的替换
     *
     * @param configuration
     * @param boundSql
     * @return
     */
    private 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.isEmpty(parameterMappings) && parameterObject != null) {
            // 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换<br>// 如果根据parameterObject.getClass()可以找到对应的类型,则替换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));

            } else {
                // MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                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;
    }

    public static class PrintSQL {
        public String sqlId;
        public String formatSQL;
    }
}
相关推荐
飞yu流星5 分钟前
C++ 函数 模板
开发语言·c++·算法
没有名字的鬼10 分钟前
C_字符数组存储汉字字符串及其索引
c语言·开发语言·数据结构
你若安好我便天晴12 分钟前
sql--MERGE INTO
数据库·sql
半桶水专家13 分钟前
go怎么终止协程的运行
数据库·sql·golang
王先生技术栈18 分钟前
思维导图,Android版本实现
java·前端
生如夏花℡20 分钟前
JAVA学习记录3
java·学习·idea
专注于开发微信小程序打工人21 分钟前
庐山派k230使用串口通信发送数据驱动四个轮子并且实现摄像头画面识别目标检测功能
开发语言·python
土豆凌凌七24 分钟前
GO:sync.Map
开发语言·后端·golang
{⌐■_■}26 分钟前
【gRPC】对称与非对称加解密和单向TLS与双向TLS讲解与go案例
java·servlet·golang
重剑无锋102442 分钟前
【《python爬虫入门教程12--重剑无峰168》】
开发语言·爬虫·python