当前位置: 首页 > article >正文

Java手动打印执行过的sql

1. 拦截器

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. 其他工具类

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;
    }
}


http://www.kler.cn/a/499971.html

相关文章:

  • 小目标检测难点分析和解决策略
  • flutter web 路由问题
  • hive数据迁移
  • 【Qt】QThread总结
  • 深度学习-81-大语言模型LLM之基于litellm与langchain与ollama启动的模型交互
  • 解决WordPress出现Fatal error: Uncaught TypeError: ftp_nlist()致命问题
  • 复古黑白恐怖迷幻眼睛纹身刺青插画潮流艺术png免抠拼贴图片素材Mindrift. Psychedelic Illustrations
  • Springboot——钉钉(站内)实现登录第三方应用
  • C++实现设计模式---访问者模式 (Visitor)
  • 解决 VSCode 调试时 Python 文件出现相对路径报错问题‘FileNotFoundError’
  • Swift 趣味开发:查找拼音首字母全部相同的 4 字成语(上)
  • 智慧充电桩可视化管理提升能源效率
  • xml简介
  • Docker中安装Tailscale方法一
  • OceanBase数据库设计与管理:构建高效分布式数据架构基石
  • Stable diffusion的SDXL模型,针不错!(含实操)
  • git push报错 unauthorized email account cannot submit code
  • 老榕树的java专题:探索 Nacos:微服务架构中的配置与服务发现利器
  • 【ArcGIS微课1000例】0138:ArcGIS栅格数据每个像元值转为Excel文本进行统计分析、做图表
  • C语言基本知识复习浓缩版:控制语句--循环
  • 汽车免拆诊断 | 2017 款东风风神 AX7 车热机后怠速不稳
  • 基于单片机的智能家居排气扇系统设计
  • 大语言模型分词器
  • MySQL库表的操作