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

拦截器实现 Mybatis Plus 打印含参数的 SQL 语句

1.实现拦截器

package com.sample.common.interceptor;import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
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.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.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;/*** @author: Alex Hu* @createTime: 2024/08/16 07:46* Custom SQL interceptor to print SQL and execution time*/
@Slf4j
public class MyBatisPlusSqlInterceptor implements InnerInterceptor {@Overridepublic void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {long startTime = System.currentTimeMillis();try {String printSql = generateSql(ms, parameter, boundSql);//Caution: this may take a long time!          executor.query(ms, parameter, rowBounds, resultHandler);long endTime = System.currentTimeMillis();long costTime = endTime - startTime;log.info("\n Time taken to execute SQL: {}ms \nExecute SQL:\n {}\n", costTime, printSql);} catch (Exception exception) {log.error("Get sql exception", exception);}}private static String generateSql(MappedStatement statement, Object parameter, BoundSql boundSql) {Configuration configuration = statement.getConfiguration();Object parameterObject = boundSql.getParameterObject();List<ParameterMapping> params = boundSql.getParameterMappings();String sql = boundSql.getSql();sql = sql.replaceAll("[\\s]+", " ");if (!ObjectUtils.isEmpty(params) && !ObjectUtils.isEmpty(parameterObject)) {TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();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);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.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));} else {sql = sql.replaceFirst("\\?", "missing");}}}}return sql;}private static String getParameterValue(Object object) {String value = "";if (object instanceof String) {value = "'" + object.toString() + "'";} else if (object instanceof Date) {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");value = "'" + format.format((Date) object) + "'";} else if (object instanceof LocalDateTime) {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");value = "'" + ((LocalDateTime) object).format(formatter) + "'";} else if (!ObjectUtils.isEmpty(object)) {value = object.toString();}return value;}
}

2.注入拦截器


@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new MyBatisPlusSqlInterceptor());...return interceptor;}
}


http://www.mrgr.cn/news/3900.html

相关文章:

  • 设计模式24-命令模式
  • django学习入门系列之第九点《案例 Flask+MySQL新增用户》
  • 【应急响应】-linux日志被删除?
  • 单例模式(饿汉式,懒汉式)
  • 计算机毕业设计选题推荐-豆瓣书籍可视化分析-Python爬虫-K-means算法
  • 【论文阅读】PRADA: Protecting Against DNN Model Stealing Attacks(2019)
  • [数据集][目标检测]流水线物件检测数据集VOC+YOLO格式9255张26类别
  • Oracle(78)什么是绑定变量(Bind Variable)?
  • 圆弧的起点端点和凸度计算圆心、离散化为多段线
  • Java 前端与后端交互:解锁 RESTful API 设计的秘密
  • pyqt5用QPainter在扇形上面描绘数据点,并可点击提示
  • 优雅处理枚举前端丢失大Long精度问题
  • Debian12安装jdk8环境
  • Real DOM, Virtual DOM, Shadow DOM,之间有什么区别
  • 【今夕是何年】雅达利发布Atari 7800+游戏主机:配备无线手柄、HDMI接口
  • 通用人工智能不应该完全以人类为标准
  • CSS的:dir()伪类:根据文本方向定制样式的指南
  • idea 项目启动慢,报内存溢出,调整jvm参数
  • 简历相关!!
  • 详解golang内存管理