首页 > 数据库 >用了MyBatis的项目 如何优雅地打印SQL

用了MyBatis的项目 如何优雅地打印SQL

时间:2024-09-23 10:24:34浏览次数:1  
标签:Object SQL 优雅 sql org MyBatis import class

前言

在使用MyBatis或者MyBatis-Plus作为ORM框架的时候,会发现默认的日志输出是下面这样的:

图片

在参数少并且SQL简单的情况下,这样的SQL我们能通过手动去替换占位符,来获取到真正执行的SQL。但是如果是比较复杂的SQL,或者查询参数比较多的话,一个个替换就比较费时费力了。

MyBatis Plugin

于是我们就可以使用MyBatis对外暴露出的Interceptor接口,来手动实现一个能优雅地打印日志的插件。平常像用的比较多的PageHelper,就是一个MyBatis的插件,实现原理和我们这次要做的功能十分相似。

最终实现后的效果是下面这样的:

图片

可以看到当前SQL语句的耗时,也能方便的查看当前的完整SQL语句

实现一个优雅打日志的功能

首先编写一个Interceptor的实现类,具体代码如下,所有的注释都放在代码上了:

其中类上的Intercepts注解含义为:在 Executor 的 query、update 方法执行前后进行自定义的处理,其中Executor 是最底层的执行器,负责与数据库进行通信。它的职责包括创建和缓存 Statement 对象、执行 SQL 语句、处理结果集等。

package com.wzy.config;
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.mapping.ParameterMapping;import org.apache.ibatis.plugin.*;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.type.TypeHandlerRegistry;import org.springframework.util.ObjectUtils;
import java.text.DateFormat;import java.util.Date;import java.util.List;import java.util.Locale;import java.util.Properties;import java.util.regex.Matcher;
/** * @ClassName SqlIntercept * @Author wzy * @qq交流 3116465773 * @Description TODO */@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}), @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})@Slf4jpublic class SqlIntercept implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 计算这一次SQL执行钱后的时间,统计一下执行耗时 long startTime = System.currentTimeMillis(); Object proceed = invocation.proceed(); long endTime = System.currentTimeMillis();
String printSql = null; try { // 通过generateSql方法拿到最终生成的SQL printSql = generateSql(invocation); } catch (Exception exception) { log.error("获取sql异常", exception); } finally { // 拼接日志打印过程 long costTime = endTime - startTime; log.info("\n 执行SQL耗时:{}ms \n 执行SQL:{}", costTime, printSql); } return proceed; }
private static String generateSql(Invocation invocation) { // 获取到BoundSql以及Configuration对象 // BoundSql 对象存储了一条具体的 SQL 语句及其相关参数信息。 // Configuration 对象保存了 MyBatis 框架运行时所有的配置信息 MappedStatement statement = (MappedStatement) invocation.getArgs()[0]; Object parameter = null; if (invocation.getArgs().length > 1) { parameter = invocation.getArgs()[1]; } Configuration configuration = statement.getConfiguration(); BoundSql boundSql = statement.getBoundSql(parameter);
// 获取参数对象 Object parameterObject = boundSql.getParameterObject(); // 获取参数映射 List<ParameterMapping> params = boundSql.getParameterMappings(); // 获取到执行的SQL String sql = boundSql.getSql(); // SQL中多个空格使用一个空格代替 sql = sql.replaceAll("[\\s]+", " "); if (!ObjectUtils.isEmpty(params) && !ObjectUtils.isEmpty(parameterObject)) { // TypeHandlerRegistry 是 MyBatis 用来管理 TypeHandler 的注册器。TypeHandler 用于在 Java 类型和 JDBC 类型之间进行转换 TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 如果参数对象的类型有对应的 TypeHandler,则使用 TypeHandler 进行处理 if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject))); } else { // 否则,逐个处理参数映射 for (ParameterMapping param : params) { // 获取参数的属性名 String propertyName = param.getProperty(); MetaObject metaObject = configuration.newMetaObject(parameterObject); // 检查对象中是否存在该属性的 getter 方法,如果存在就取出来进行替换 if (metaObject.hasGetter(propertyName)) { Object obj = metaObject.getValue(propertyName); sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); // 检查 BoundSql 对象中是否存在附加参数。附加参数可能是在动态 SQL 处理中生成的,有的话就进行替换 } else if (boundSql.hasAdditionalParameter(propertyName)) { Object obj = boundSql.getAdditionalParameter(propertyName); sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); } else { // 如果都没有,说明SQL匹配不上,带上“缺失”方便找问题 sql = sql.replaceFirst("\\?", "缺失"); } } } } return sql; }
private static String getParameterValue(Object object) { String value = ""; if (object instanceof String) { value = "'" + object.toString() + "'"; } else if (object instanceof Date) { DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); value = "'" + format.format((Date) object) + "'"; } else if (!ObjectUtils.isEmpty(object)) { value = object.toString(); } return value; }
@Override public Object plugin(Object target) { return Plugin.wrap(target, this); }
@Override public void setProperties(Properties properties) { // 可以通过properties配置插件参数 }}

 

接着编写一个MyBatis的配置类,将这个插件注册进去

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;import com.mybatisflex.test.Interceptor.SqlInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class MyBatisConfig { @Bean public ConfigurationCustomizer mybatisConfigurationCustomizer() { return configuration -> { configuration.addInterceptor(new SqlInterceptor()); }; }}

标签:Object,SQL,优雅,sql,org,MyBatis,import,class
From: https://www.cnblogs.com/qxqbk/p/18426529

相关文章

  • SqlServer巡检
    微信公众平台(qq.com)1、检查数据库最大最小内存配置SELECT[name],[value],[value_in_use]FROMsys.configurationsWHERE[name]='maxservermemory(MB)'OR [name]='minservermemory(MB)';2、内存使用情况检查脚本SELECTtotal_physical_memory_kb/1024......
  • Transact-SQL概述(SQL Server 2022)
    新书速览|SQLServer2022从入门到精通:视频教学超值版_sqlserver2022出版社-CSDN博客《SQLServer2022从入门到精通(视频教学超值版)(数据库技术丛书)》(王英英)【摘要书评试读】-京东图书(jd.com)SQLServer数据库技术_夏天又到了的博客-CSDN博客在前面的章节中,其实已......
  • mysql5.7.40升级到5.7.44
    1.软件下载https://www.mysql.com/downloads/找到mysqlcommunityGPLdownload--mysqlcommunityserver--选择5.7.44和rhel/oracle下载mysql-5.7.44-1.el7.x86_64.rpm-bundle.tar2.停服备份systemctlstopmysqldcp/etc/my.cnf/etc/my.cnf.bak20240801配置文件tar-z......
  • 在esm中优雅的使用__dirname
    在esm中没有这些__dirname、require,因为这是cjs的规范。但是通过如下代码,你即可使用上importpathfrom"node:path";import{createRequire}from"node:module";import{fileURLToPath}from"node:url";//定义一个全局变量__dirnameletdirnameVal=''......
  • 网站数据库错误的原因通常包括配置错误、编码错误、硬件故障、网络问题、数据损坏、权
    网站数据库错误可能由多种因素引起,主要包括以下几点:配置错误:数据库或应用程序的配置不当可能导致连接失败或其他运行时错误。编码错误:程序中的逻辑错误或语法错误也可能导致数据库操作失败。硬件故障:服务器硬件出现问题,如硬盘损坏、内存故障等,会影响数据库的正常运行。网络问......
  • 出现这种报错怎么办?SQLSTATE[HY000]: General error: 1615 Prepared statement needs
    如果你遇到由于数据库配置问题导致前后台无法打开的情况,可以通过修改数据库配置文件来解决。具体步骤如下:解决步骤第一步:打开数据库配置文件使用Notepad++打开配置文件:使用Notepad++或其他专业文本编辑器打开数据库配置文件 application/database.php。例如,假设你的......
  • SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared
    当遇到由于数据库配置问题导致前后台无法打开的情况时,可以通过修改数据库配置文件来解决问题。具体步骤如下:1.准备工作备份数据库配置文件:在修改前,建议先备份 application/database.php 文件。sh cpapplication/database.phpapplication/database.php.bak准......
  • 报错:SQLSTATE[HY000]:General error:145 Table './**@002******@/002ecn/ey_config' is
    错误信息 SQLSTATE[HY000]:Generalerror:145Table'./**@002******@/002ecn/ey_config'ismarkedascrashedandshouldberepaired 表明MySQL数据库中的表 ey_config 已经损坏,并且需要修复。解决方案1.修复损坏的表登录数据库:使用命令行或其他数据库管理工具......
  • SQL Server的Descending Indexes降序索引
    SQLServer的DescendingIndexes降序索引   背景索引是关系型数据库中优化查询性能的重要手段之一。对于需要处理大量数据的场景,合理的索引策略能够显著减少查询时间。特别是在涉及多字段排序的复杂查询中,选择合适的索引类型(如降序索引)显得尤为重要。本文将探讨如何在SQL......
  • SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xF0\x9F...' for
    错误信息 SQLSTATE[HY000]:Generalerror:1366Incorrectstringvalue:'\xF0\x9F...'forcolumn'content'atrow1 表示在插入数据时,content 字段的内容包含了一些不支持的特殊字符(如表情符号),导致插入失败。这是因为MySQL的 utf8 编码不支持某些四字节的Unicode字......