From 4242128e8980734889a01a1ac429393b51073894 Mon Sep 17 00:00:00 2001
From: liurunyu <lry9898@163.com>
Date: 星期三, 21 五月 2025 11:42:42 +0800
Subject: [PATCH] 重新设计mybatis插件实现方式,增加输出sql日志插件
---
pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlHelp.java | 123 ++++++++++++++++++++++++
pms-parent/pms-common/src/main/java/com/dy/common/mybatis/MyBatisConfig.java | 63 ++++++++++--
pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlInterceptor.java | 63 ++++++++++++
3 files changed, 239 insertions(+), 10 deletions(-)
diff --git a/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/MyBatisConfig.java b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/MyBatisConfig.java
index 7f450f8..bd2f4ae 100644
--- a/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/MyBatisConfig.java
+++ b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/MyBatisConfig.java
@@ -4,27 +4,70 @@
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
+import jakarta.annotation.PostConstruct;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
-@org.springframework.context.annotation.Configuration
+import java.util.List;
+
+@Configuration
public class MyBatisConfig {
+ @Autowired
+ private List<SqlSessionFactory> sqlSessionFactoryList;
+
+ @Value("${mybatis-plus.configuration.print-sql}")
+ private boolean printSql;
+
+ /**
+ * 涓や釜鎷︽埅鍣紝鑷姩鐢熸垚ID锛屽紓甯告椂杈撳嚭SQL
+ */
+ @PostConstruct
+ public void addMyInterceptor() {
+ for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
+ org.apache.ibatis.session.Configuration conf = sqlSessionFactory.getConfiguration();
+ conf.addInterceptor(new AutoGenerateIdInterceptor());
+ conf.addInterceptor(new PrintExceptionSqlInterceptor());
+ if (printSql) {
+ conf.addInterceptor(new PrintSqlInterceptor());
+ }
+ }
+ }
+
+ /**
+ * mybatisPlus鐨勫垎闈㈡彃浠�
+ * @return 鎷︽埅鍣�
+ */
+ @Bean
+ public PaginationInnerInterceptor paginationInnerInterceptor(){
+ return new PaginationInnerInterceptor() ;
+ }
+
+
+ /*
+ @Value("${mybatis-plus.configuration.print-sql}")
+ private boolean printSql;
@Bean
public ConfigurationCustomizer mybatisConfigurationCustomizer() {
return configuration -> {
configuration.addInterceptor(new AutoGenerateIdInterceptor());
configuration.addInterceptor(new PrintExceptionSqlInterceptor());
- };
- /*
- return new ConfigurationCustomizer() {
- @Override
- public void customize(MybatisConfiguration configuration) {
- configuration.addInterceptor(new AutoGenerateIdInterceptor());
- configuration.addInterceptor(new PrintExceptionSqlInterceptor());
+ if (printSql) {
+ configuration.addInterceptor(new PrintSqlInterceptor());
}
};
- */
+ //return new ConfigurationCustomizer() {
+ // @Override
+ // public void customize(MybatisConfiguration configuration) {
+ // configuration.addInterceptor(new AutoGenerateIdInterceptor());
+ // configuration.addInterceptor(new PrintExceptionSqlInterceptor());
+ // }
+ //};
}
+
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
@@ -32,5 +75,5 @@
// 濡傛灉鏈夊鏁版嵁婧愬彲浠ヤ笉閰嶅叿浣撶被鍨�, 鍚﹀垯閮藉缓璁厤涓婂叿浣撶殑 DbType
return interceptor;
}
-
+ */
}
diff --git a/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlHelp.java b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlHelp.java
new file mode 100644
index 0000000..dbad98f
--- /dev/null
+++ b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlHelp.java
@@ -0,0 +1,123 @@
+package com.dy.common.mybatis;
+
+import org.apache.ibatis.mapping.BoundSql;
+import org.apache.ibatis.mapping.ParameterMapping;
+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.Locale;
+
+/**
+ * @Author: liurunyu
+ * @Date: 2025/5/20 15:31
+ * @Description
+ */
+public class PrintSqlHelp {
+
+ /**
+ * 鑾峰彇瀹屾暣鐨勬墽琛孲QL
+ */
+ public static String getFullSql(Configuration configuration, BoundSql boundSql) {
+ try {
+ return parseAndExtractFullSql(configuration, boundSql);
+ } catch (Exception e) {
+ // 濡傛灉瑙f瀽澶辫触杩斿洖鍘熷SQL
+ return boundSql.getSql();
+ }
+ }
+
+ /**
+ * 缁勮瀹屾暣鐨剆ql璇彞骞舵妸瀵瑰簲鐨勫弬鏁伴兘浠e叆鍒皊ql璇彞閲岄潰
+ *
+ * @param configuration Configuration
+ * @param boundSql BoundSql
+ * @return sql瀹屾暣璇彞
+ */
+ private static String parseAndExtractFullSql(Configuration configuration, BoundSql boundSql) {
+ // 鑾峰彇mapper閲岄潰鏂规硶涓婄殑鍙傛暟
+ Object sqlParameter = boundSql.getParameterObject();
+ // sql璇彞閲岄潰闇�瑕佺殑鍙傛暟
+ List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
+ // sql鍘熷璇彞(?杩樻病鏈夋浛鎹㈡垚鎴戜滑鍏蜂綋鐨勫弬鏁�)
+ String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
+ if (!parameterMappings.isEmpty() && sqlParameter != null) {
+ // sql璇彞閲岄潰鐨�?鏇挎崲鎴愮湡瀹炵殑鍙傛暟
+ TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
+ if (typeHandlerRegistry.hasTypeHandler(sqlParameter.getClass())) {
+ sql = sql.replaceFirst("\\?", getParameterValue(sqlParameter));
+ } else {
+ MetaObject metaObject = configuration.newMetaObject(sqlParameter);
+ for (ParameterMapping parameterMapping : parameterMappings) {
+ // 鎸夐『搴忔妸?鏇挎崲鎴愬搴旂殑鍊�
+ String propertyName = parameterMapping.getProperty();
+ if (metaObject.hasGetter(propertyName)) {
+ Object obj = metaObject.getValue(propertyName);
+ sql = sql.replaceFirst("\\?", getParameterValue(obj));
+ } else if (boundSql.hasAdditionalParameter(propertyName)) {
+ Object obj = boundSql.getAdditionalParameter(propertyName);
+ sql = sql.replaceFirst("\\?", getParameterValue(obj));
+ }
+ }
+ }
+ }
+ return sql;
+ }
+
+
+ /**
+ * 鑾峰彇鍙傛暟瀵瑰簲鐨剆tring鍊�
+ *
+ * @param obj 鍙傛暟瀵瑰簲鐨勫��
+ * @return string
+ */
+ private static String getParameterValue(Object obj) {
+ String value;
+ if (obj instanceof String) {
+ value = "'" + obj + "'";
+ } else if (obj instanceof Date) {
+ DateFormat formatter =
+ DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
+ value = "'" + formatter.format(obj) + "'";
+ } else {
+ if (obj != null) {
+ value = obj.toString();
+ } else {
+ value = "";
+ }
+ }
+ // 瀵圭壒娈婂瓧绗﹁繘琛岃浆涔夛紝鏂逛究涔嬪悗澶勭悊鏇挎崲
+ return value != null ? makeQueryStringAllRegExp(value) : "";
+ }
+
+
+
+ /**
+ * 杞箟姝e垯鐗规畩瀛楃 锛�$()*+.[]?\^{}
+ * \\闇�瑕佺涓�涓浛鎹紝鍚﹀垯replace鏂规硶鏇挎崲鏃朵細鏈夐�昏緫bug
+ */
+ private static String makeQueryStringAllRegExp(String str) {
+ if (str != null && !"".equals(str)) {
+ return str.replace("\\", "\\\\")
+ .replace("*", "\\*")
+ .replace("+", "\\+")
+ .replace("|", "\\|")
+ .replace("{", "\\{")
+ .replace("}", "\\}")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ .replace("^", "\\^")
+ .replace("$", "\\$")
+ .replace("[", "\\[")
+ .replace("]", "\\]")
+ .replace("?", "\\?")
+ .replace(",", "\\,")
+ .replace(".", "\\.")
+ .replace("&", "\\&");
+ }
+ return str;
+ }
+}
diff --git a/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlInterceptor.java b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlInterceptor.java
new file mode 100644
index 0000000..f9bbaa9
--- /dev/null
+++ b/pms-parent/pms-common/src/main/java/com/dy/common/mybatis/PrintSqlInterceptor.java
@@ -0,0 +1,63 @@
+package com.dy.common.mybatis;
+
+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.plugin.Interceptor;
+import org.apache.ibatis.plugin.Intercepts;
+import org.apache.ibatis.plugin.Invocation;
+import org.apache.ibatis.plugin.Signature;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.ResultHandler;
+import org.apache.ibatis.session.RowBounds;
+
+/**
+ * @Author: liurunyu
+ * @Date: 2025/5/20 15:31
+ * @Description
+ */
+/**
+ * 鎷︽埅鎵цSQL鎵ц鍦烘櫙锛屽苟灏哠QL鎵撳嵃鍑烘潵
+ * 鎷︽埅Executor閲岄潰鐨剄uery鍜寀pdate鏂规硶
+ */
+@Intercepts({
+ @Signature(
+ method = "query",
+ type = Executor.class,
+ args = {
+ MappedStatement.class,
+ Object.class,
+ RowBounds.class,
+ ResultHandler.class
+ }
+ ),
+ @Signature(
+ type = Executor.class,
+ method = "update",
+ args = {
+ MappedStatement.class,
+ Object.class
+ }
+ )
+})
+@Slf4j
+public class PrintSqlInterceptor implements Interceptor {
+ @Override
+ public Object intercept(Invocation invocation) throws Throwable {
+ Object[] args = invocation.getArgs();
+
+ if (args != null && args.length > 1) {
+ MappedStatement mappedStatement = (MappedStatement) args[0];
+ Object parameter = args[1];
+
+ String sqlId = mappedStatement.getId();
+ BoundSql boundSql = mappedStatement.getBoundSql(parameter);
+ Configuration configuration = mappedStatement.getConfiguration();
+ log.info("\nSQL Id: " + sqlId + "\nSQL Parameters: " + boundSql.getParameterObject() + "\nSQL: " + PrintSqlHelp.getFullSql(configuration, boundSql) + "\n");
+ }
+
+ return invocation.proceed();
+ }
+
+}
--
Gitblit v1.8.0