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;
    }
}
相关推荐
&岁月不待人&2 分钟前
Android 常用设计模式和实例
java·开发语言·设计模式
qq_139484288211 分钟前
springboot239-springboot在线医疗问答平台(源码+论文+PPT+部署讲解等)
java·数据库·spring boot·后端·spring·maven·intellij-idea
蔚一11 分钟前
微服务SpringCloud Alibaba组件nacos教程【详解naocs基础使用、服务中心配置、集群配置,附有案例+示例代码】
java·后端·spring cloud·微服务·架构·intellij-idea·springboot
神仙别闹15 分钟前
基于Springmvc+MyBatis+Spring+Bootstrap+EasyUI+Mysql的个人博客系统
java·mysql·ssm
计算机小白一个18 分钟前
蓝桥杯 Java B 组之函数定义与递归入门
java·算法·职场和发展·蓝桥杯
Hello.Reader43 分钟前
将错误消息输出到标准错误流:Rust中的最佳实践
开发语言·后端·rust
用键盘当武器的秋刀鱼1 小时前
Spring boot(maven) - Mybatis 超级入门版
java·spring boot·mybatis
管大虾1 小时前
设计模式-适配器模式
java·设计模式·适配器模式
无限大.1 小时前
前端知识速记--JS篇:instanceof
开发语言·前端·javascript
Shinka-深深1 小时前
《图解设计模式》笔记(八)管理状态
java·笔记·设计模式