MyBatis(Plus) 打印SQL, 分析执行时间
MyBatis/MyBatis Plus打印的SQL调试起来比较麻烦
当然IDEA/eclipse都有类似mybatis log plugin这种插件来解析, 但是安装插件有些许弊端, 就写了个工具类处理
如果需要更详细的SQL分析, 建议使用p6spy. 本配置仅仅是为了调试SQL方便
效果展示:

代码:
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, 分析执行时间的更多相关文章
- MyBatis 插件 : 打印 SQL 及其执行时间
Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用: Executor(update. ...
- mybatis日志,打印sql语句,输出sql
mybatis日志,打印sql语句,输出sql<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE ...
- mybatis配置打印sql
mybatis配置打印sql: <settings> <setting name="logImpl" value="STDOUT_LOGGING&quo ...
- Springboot中mybatis控制台打印sql语句
Springboot中mybatis控制台打印sql语句 https://www.jianshu.com/p/3cfe5f6e9174 https://www.jianshu.com/go-wild? ...
- Springboot自定义starter打印sql及其执行时间
前面写到了通过实现mybatis提供的org.apache.ibatis.plugin.Interceptor接口实现了打印SQL执行时间,并格式化SQL及其参数,如果我们使用的是ssm还得再配置文件 ...
- mybatis 控制台打印sql
开发时调试使用 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBe ...
- mybatis 控制台打印sql语句
其实很简单,打印SQL只需要加一个setting就可以了.亲测可用. mybatis-config.xml: <settings> <setting name=&quo ...
- spring-mvc Mybatis插件打印SQL
代码: package com.chainup.exchange.service.adapter; import com.chainup.exchange.service.impl.AccountSe ...
- mybatis logback打印sql
<?xml version="1.0" encoding="UTF-8" ?><configuration> <contextNa ...
- Mybatis控制台打印SQL语句的两种方式
问题描述在使用mybatis进行开发的时候,由于可以动态拼接sql,这样大大方便了我们.但是也有一定的问题,当我们动态sql拼接的块很多的时候,我们要想从*mapper.xml中直接找出完整的sql就 ...
随机推荐
- 【KAWAKO】在windows上用CMake和MinGW编译c++工程
目录 安装CMake 安装MinGW 编写CMakeLists.txt 编译一条龙 安装CMake 在网上随便找个教程照着安装就行了,不再赘述. 安装MinGW 参考这篇博客.从MinGW官网下载的安 ...
- 11款Linux数据恢复工具!
转载:<Linux就该这么学> - 必读的Linux系统与红帽RHCE认证免费自学书籍 (linuxprobe.com) 11款最棒的Linux数据恢复工具发布啦! | <Linux ...
- 推荐一个Dapper扩展CRUD基本操作的开源库
在C#众多ORM框架中,Dapper绝对称得上微型ORM之王,Dapper以灵活.性能好而著名,同样也是支持各种数据库,但是对于一些复杂的查询,我们写原生的SQL语句问题不大,对于CRUD基本操作,我 ...
- 任何人均可上手的数据库与API搭建平台
编写API可能对于很多后端开发人员来说,并不是什么难事儿,但如果您主要从事前端功能,那么可能还是有一些门槛. 那么有没有工具可以帮助我们降低编写API的学习门槛和复杂度呢? 今天就来给大家推荐一个不错 ...
- 一文吃透 Go 内置 RPC 原理
hello 大家好呀,我是小楼,这是系列文<Go底层原理剖析>的第三篇,依旧分析 Http 模块.我们今天来看 Go内置的 RPC.说起 RPC 大家想到的一般是框架,Go 作为编程语言竟 ...
- 工业仿真:Chai 3D之点云技术
推荐:将 NSDT场景编辑器 加入你的3D开发工具链. 介绍 点云是三维坐标系中的一组数据点.在 CHAI3D 中,这些点由 X.Y 和 Z 坐标定义,通常用于表示对象的外表面. 点云可以由3 ...
- 红米note9 刷开机第一屏logo
参考:https://romprovider.com/change-boot-logo-redmi-9-prime/ 工具:https://sites.google.com/site/kadanuti ...
- 微信小程序与微信公众号之间支付问题解决方案
前言 大家好,我是一名对编程有兴趣的小伙子,IT届称我为xiager,工作中叫我jake 就好了,如果此文对你有帮助希望多多关注哦. 准备 微信公众平台 微信支付平台 微信开放平台 一. 小程序 ...
- css 属性选择器需要加引号吗
平常我们是不加引号的: HTML: <div data-a='aq1'>99</div> CSS: [data-a=aq1]{ color: #f00; } 想加上也行 ...
- 【补题】第 46 届 ICPC EC Final
比赛 题目:第 46 届 ICPC EC Final(正式赛) 榜单 A. DFS Order 签到题 容易发现对于一个点,它的最小位置就是从根走一条链直接到它,最大位置就是除了它的子树,其它全已经走 ...