MyBatis/MyBatis Plus打印的SQL调试起来比较麻烦

当然IDEA/eclipse都有类似mybatis log plugin这种插件来解析, 但是安装插件有些许弊端, 就写了个工具类处理

如果需要更详细的SQL分析, 建议使用p6spy. 本配置仅仅是为了调试SQL方便

效果展示:

代码:

github

package kim.nzxy.ly.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; import java.sql.Statement;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; /**
* mybatis sql 日志拦截器, 用于打印SQL
*
* @author ly-chn
*/
@Slf4j
@Profile("local")
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
public class MybatisLogSqlInterceptor implements Interceptor {
private static final Set<String> NEED_BRACKETS =
Set.of("String", "Date", "Time", "LocalDate", "LocalTime", "LocalDateTime", "BigDecimal", "Timestamp"); private Configuration configuration = null; @Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
long startTime = System.currentTimeMillis();
try {
// 如需打印结果, 返回值即结果集
return invocation.proceed();
} finally {
long sqlCost = System.currentTimeMillis() - startTime;
String sql = this.getSql(target);
log.info("sql took {}ms: {}", sqlCost, sql);
}
} /**
* 获取sql
*/
private String getSql(Object target) {
try {
StatementHandler statementHandler = (StatementHandler) target;
BoundSql boundSql = statementHandler.getBoundSql();
if (configuration == null) {
final ParameterHandler parameterHandler = statementHandler.getParameterHandler();
this.configuration = (Configuration) FieldUtils.readField(parameterHandler, "configuration", true);
}
// 替换参数格式化Sql语句,去除换行符
return formatSql(boundSql, configuration);
} catch (Exception e) {
log.warn("get sql error {}", target, e);
return "failed to parse sql";
}
} /**
* 获取完整的sql实体的信息
*/
private String formatSql(BoundSql boundSql, Configuration configuration) {
String sql = boundSql.getSql();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
Object parameterObject = boundSql.getParameterObject();
// 输入sql字符串空判断
if (StringUtils.isEmpty(sql) || Objects.isNull(configuration)) {
return "";
} TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 替换空格容易造成本身存在空格的查询条件被替换
sql = sql.replaceAll("[\n\r ]+", " "); if (parameterMappings == null) {
return sql;
} parameterMappings = parameterMappings.stream().filter(it -> it.getMode() != ParameterMode.OUT).collect(Collectors.toList()); final StringBuilder result = new StringBuilder(sql); // 解析问号并填充
for (int i = result.length(); i > 0; i--) {
if (result.charAt(i - 1) != '?') {
continue;
}
ParameterMapping parameterMapping = parameterMappings.get(parameterMappings.size() - 1);
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
if (value != null) {
String type = value.getClass().getSimpleName();
if (NEED_BRACKETS.contains(type)) {
result.replace(i - 1, i, "'" + value + "'");
} else {
result.replace(i - 1, i, value.toString());
}
} else {
result.replace(i - 1, i, "null");
}
parameterMappings.remove(parameterMappings.size() - 1);
}
return result.toString();
}
}

MyBatis(Plus) 打印SQL, 分析执行时间的更多相关文章

  1. MyBatis 插件 : 打印 SQL 及其执行时间

    Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用: Executor(update. ...

  2. mybatis日志,打印sql语句,输出sql

    mybatis日志,打印sql语句,输出sql<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE ...

  3. mybatis配置打印sql

    mybatis配置打印sql: <settings> <setting name="logImpl" value="STDOUT_LOGGING&quo ...

  4. Springboot中mybatis控制台打印sql语句

    Springboot中mybatis控制台打印sql语句 https://www.jianshu.com/p/3cfe5f6e9174 https://www.jianshu.com/go-wild? ...

  5. Springboot自定义starter打印sql及其执行时间

    前面写到了通过实现mybatis提供的org.apache.ibatis.plugin.Interceptor接口实现了打印SQL执行时间,并格式化SQL及其参数,如果我们使用的是ssm还得再配置文件 ...

  6. mybatis 控制台打印sql

    开发时调试使用 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBe ...

  7. mybatis 控制台打印sql语句

    其实很简单,打印SQL只需要加一个setting就可以了.亲测可用. mybatis-config.xml: <settings>        <setting name=&quo ...

  8. spring-mvc Mybatis插件打印SQL

    代码: package com.chainup.exchange.service.adapter; import com.chainup.exchange.service.impl.AccountSe ...

  9. mybatis logback打印sql

    <?xml version="1.0" encoding="UTF-8" ?><configuration> <contextNa ...

  10. Mybatis控制台打印SQL语句的两种方式

    问题描述在使用mybatis进行开发的时候,由于可以动态拼接sql,这样大大方便了我们.但是也有一定的问题,当我们动态sql拼接的块很多的时候,我们要想从*mapper.xml中直接找出完整的sql就 ...

随机推荐

  1. Hyperledger Fabric部署与测试(Ubuntu)

    Fabric部署与测试 Fabric部署与测试最正确的还是参照官方链接:Hyperledger Fabric官方链接 ok,接下来开始部署Fabric.(以Ubuntu为例) 一.部署Fabric 1 ...

  2. 华为云CodeArts Artifact,5大特性守护制品质量与安全

    摘要:2023年2月23日,华为云CodeArts Artifact制品仓库服务正式上线,目标进一步赋能企业伙伴与开发者,实现软件作业中可信制品生产与应用活动快速落地,提高软件交付效率与质量. 本文分 ...

  3. CF1742G Orray

    题目传送门 思路 大抵算是一道位运算入门题? 首先为了使 \(b_i\) 的字典序最大,我们注意到 \(b_1=a_1\),所以 \(a_1\) 必然是序列中最大的那个数. 接下来考虑贪心,设当前已经 ...

  4. Flutter:学习 StatelessWidget 和 StatefulWidget

    Widget 分为了两种类型,分别为 StatelessWidget 和 StatefulWidget. 顾名思义,StatelessWidget 就是无状态的组件,它只是作为一个不发生任何更新状态的 ...

  5. LeetCode-1706 球会落在何处

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/where-will-the-ball-fall 题目描述 用一个大小为 m x n 的二维网格 ...

  6. Canonical为所有支持的Ubuntu LTS系统发布了新的Linux内核更新

    Canonical近日为所有支持的Ubuntu LTS系统发布了新的Linux内核更新,以解决总共19个安全漏洞. 新的Ubuntu内核更新仅适用于长期支持的Ubuntu系统,包括Ubuntu 22. ...

  7. 子路由path路径带 ‘/‘与不带

    子路由不带 / : $router.push('/layout/home') 浏览器地址栏显示: http:xxxxxxxxxx/layout/home 带 / : $router.push('/us ...

  8. Python (进阶 第二部)

    目录 函数 闭包 匿名函数 迭代器 高阶函数 推导式 递归函数 函数 函数的定义:  功能( 包括一部分代码,实现某种功能,达成某个目的) 函数的特点:  函数可以反复调用 ,提高代码的复用性,提高开 ...

  9. E-MU1212m(E-MU1616m)在Win10(Win11)中的驱动安装

    创新(Creative)公司早期生产的专业PCI声卡E-MU1212m及E-MU1616m当前二手市场上的性价比非常高,但由于生产年代久远,其驱动程序最高只支持到Windows vista版本,经过实 ...

  10. mysql8.0.30主从配置

    安装包下载地址: https://downloads.mysql.com/archives/community/ 1. 解压介质包: # tar xf mysql-8.0.30-linux-glibc ...