mybatis plus intercept修改sql

2024-03-28 16:04

本文主要是介绍mybatis plus intercept修改sql,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原始需求

在SQL语句前面加上一个request-id

问题描述

今天收到业务同学反馈,说接入某个SDK后,request-id本地debug发现sql已经修改了,但打印的sql中却没有request-id信息

在这里插入图片描述

在这里插入图片描述

看了下代码,发现用户的代码其实就是下方 方案一代码,取不到的原因也在代码中注释了

方案一

package com.jiankunking.mybatisplus;import static org.apache.commons.lang3.StringUtils.isNotBlank;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.jiankunking.utils.JkkLogUtil;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;@Intercepts({@Signature(type = StatementHandler.class, method = "prepare",args = {Connection.class, Integer.class}),@Signature(type = StatementHandler.class, method = "getBoundSql", args = {}),@Signature(type = Executor.class, method = "update",args = {MappedStatement.class, Object.class}),@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}),}
)
@Slf4j
public class MybatisPlusRequestIdInterceptor extends MybatisPlusInterceptor {private Boolean enabled = true;@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object target = invocation.getTarget();Object[] args = invocation.getArgs();BoundSql boundSql = null;if (target instanceof Executor) {Object parameter = args[1];boolean isUpdate = args.length == 2;MappedStatement ms = (MappedStatement) args[0];if (!isUpdate && ms.getSqlCommandType() == SqlCommandType.SELECT) {RowBounds rowBounds = (RowBounds) args[2];if (args.length == 4) {boundSql = ms.getBoundSql(parameter);} else {// 几乎不可能走进这里面,除非使用Executor的代理对象调用query[args[6]]boundSql = (BoundSql) args[5];}}} else {StatementHandler statementHandler = (StatementHandler) target;boundSql = statementHandler.getBoundSql();}if (enabled && boundSql != null) {String sql = boundSql.getSql();String requestId = JkkLogUtil.getCurrentRequestId();StringBuilder sb = new StringBuilder("/*");if (isNotBlank(requestId) && isNotBlank(sql)) {sb.append(" Jkk-request-id:").append(requestId).append(" ");}String armsTraceId = JkkLogUtil.getTraceId();if (isNotBlank(armsTraceId) && isNotBlank(sql)) {sb.append(" trace-id:").append(armsTraceId).append(" ");}String armsRpcId = JkkLogUtil.getRpcId();if (isNotBlank(armsRpcId)) {sb.append(" rpc-id:").append(armsRpcId).append(" ");}sb.append(" */");sb.append(sql);// 通过反射修改sql语句Field field = boundSql.getClass().getDeclaredField("sql");field.setAccessible(true);field.set(boundSql, sb.toString());// 这里如果不调用 return invocation.proceed();// 而是执行父类intercept的话,会导致反射修改的SQL无效// 因为父类获取sql还是基于参数再次拼接的没有直接使用boundSql}return super.intercept(invocation);}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {enabled = Boolean.valueOf(properties.getProperty("enabled", "true"));}
}

方案二

直接修改mybatisplus的Statement

package com.jiankunking.mybatisplus;import static org.apache.commons.lang3.StringUtils.isNotBlank;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.jiankunking.utils.JkkLogUtil;import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;@Intercepts({@Signature(type = StatementHandler.class, method = "prepare",args = {Connection.class, Integer.class}),@Signature(type = StatementHandler.class, method = "getBoundSql", args = {}),@Signature(type = Executor.class, method = "update",args = {MappedStatement.class, Object.class}),@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}),}
)
@Slf4j
public class MybatisPlusRequestIdInterceptor extends MybatisPlusInterceptor {private Boolean enabled = true;@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object target = invocation.getTarget();Object[] args = invocation.getArgs();BoundSql boundSql = null;if (target instanceof Executor) {Object parameter = args[1];boolean isUpdate = args.length == 2;MappedStatement ms = (MappedStatement) args[0];if (!isUpdate && ms.getSqlCommandType() == SqlCommandType.SELECT) {RowBounds rowBounds = (RowBounds) args[2];if (args.length == 4) {boundSql = ms.getBoundSql(parameter);} else {// 几乎不可能走进这里面,除非使用Executor的代理对象调用query[args[6]]boundSql = (BoundSql) args[5];}}} else {StatementHandler statementHandler = (StatementHandler) target;boundSql = statementHandler.getBoundSql();}if (enabled && boundSql != null) {String sql = boundSql.getSql();String requestId = JkkLogUtil.getCurrentRequestId();StringBuilder sb = new StringBuilder("/*");if (isNotBlank(requestId) && isNotBlank(sql)) {sb.append(" Jkk-request-id:").append(requestId).append(" ");}String armsTraceId = JkkLogUtil.getTraceId();if (isNotBlank(armsTraceId) && isNotBlank(sql)) {sb.append(" trace-id:").append(armsTraceId).append(" ");}String armsRpcId = JkkLogUtil.getRpcId();if (isNotBlank(armsRpcId)) {sb.append(" rpc-id:").append(armsRpcId).append(" ");}sb.append(" */");sb.append(sql);// 通过反射修改sql语句//Field field = boundSql.getClass().getDeclaredField("sql");//field.setAccessible(true);//field.set(boundSql, sb.toString());if (target instanceof Executor) {setCurrentSql(invocation, sb.toString());} else {StatementHandler statementHandler = (StatementHandler) target;MetaObject metaObject = SystemMetaObject.forObject(statementHandler);metaObject.setValue("delegate.boundSql.sql", sb.toString());}}return super.intercept(invocation);}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {enabled = Boolean.valueOf(properties.getProperty("enabled", "true"));}private static final int MAPPED_STATEMENT_INDEX = 0;private static final int PARAM_OBJ_INDEX = 1;private void setCurrentSql(Invocation invocation, String sql) {Object[] args = invocation.getArgs();Object paramObj = args[PARAM_OBJ_INDEX];MappedStatement mappedStatement = (MappedStatement) args[MAPPED_STATEMENT_INDEX];BoundSql boundSql = mappedStatement.getBoundSql(paramObj);MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(boundSql));MetaObject metaObject = MetaObject.forObject(newMappedStatement,new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),new DefaultReflectorFactory());metaObject.setValue("sqlSource.boundSql.sql", sql);args[MAPPED_STATEMENT_INDEX] = newMappedStatement;}private class BoundSqlSqlSource implements SqlSource {BoundSql boundSql;public BoundSqlSqlSource(BoundSql boundSql) {this.boundSql = boundSql;}public BoundSql getBoundSql(Object parameterObject) {return boundSql;}}@SuppressWarnings({"unchecked", "rawtypes"})private MappedStatement copyFromMappedStatement(MappedStatement ms,SqlSource newSqlSource) {MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());builder.resource(ms.getResource());builder.fetchSize(ms.getFetchSize());builder.statementType(ms.getStatementType());builder.keyGenerator(ms.getKeyGenerator());// setStatementTimeout()builder.timeout(ms.getTimeout());// setParameterMap()builder.parameterMap(ms.getParameterMap());// setStatementResultMap()List<ResultMap> resultMaps = new ArrayList<ResultMap>();String id = "-inline";if (ms.getResultMaps() != null) {id = ms.getResultMaps().get(0).getId() + "-inline";}ResultMap resultMap = new ResultMap.Builder(null, id, Long.class,new ArrayList()).build();resultMaps.add(resultMap);builder.resultMaps(resultMaps);builder.resultSetType(ms.getResultSetType());// setStatementCache()builder.cache(ms.getCache());builder.flushCacheRequired(ms.isFlushCacheRequired());builder.useCache(ms.isUseCache());return builder.build();}//private MappedStatement getMappedStatement(Invocation invo) {//    Object[] args = invo.getArgs();//    Object mappedStatement = args[MAPPED_STATEMENT_INDEX];//    return (MappedStatement) mappedStatement;//}
}

方案三

package com.jiankunking.mybatisplus;import static org.apache.commons.lang3.StringUtils.isNotBlank;import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.jiankunking.utils.JkkLogUtil;
import java.sql.Connection;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;@Slf4j
public class MybatisPlusRequestIdInterceptor implements InnerInterceptor {@Overridepublic void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {try {PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();String sql = mpBs.sql();if (StringUtils.isBlank(sql)) {return;}StringBuilder sb = new StringBuilder("/*");String requestId = JkkLogUtil.getCurrentRequestId();if (isNotBlank(requestId)) {sb.append(" Jkk-request-id:").append(requestId).append(" ");}String armsTraceId = JkkLogUtil.getTraceId();if (StringUtils.isNotBlank(armsTraceId)) {sb.append(" trace-id:").append(armsTraceId).append(" ");}String armsRpcId = JkkLogUtil.getRpcId();if (StringUtils.isNotBlank(armsRpcId)) {sb.append(" rpc-id:").append(armsRpcId).append(" ");}sb.append(" */");sb.append(sql);mpBs.sql(sb.toString());} catch (Exception e) {log.error("beforePrepare has error", e);}}
}

这篇关于mybatis plus intercept修改sql的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/856061

相关文章

MySQL中的事务隔离级别详解

《MySQL中的事务隔离级别详解》在MySQL中,事务(Transaction)是一个执行单元,它要么完全执行,要么完全回滚,以保证数据的完整性和一致性,下面给大家介绍MySQL中的事务隔离级别详解,... 目录一、事务并发问题二、mysql 事务隔离级别1. READ UNCOMMITTED(读未提交)2

Python对PDF书签进行添加,修改提取和删除操作

《Python对PDF书签进行添加,修改提取和删除操作》PDF书签是PDF文件中的导航工具,通常包含一个标题和一个跳转位置,本教程将详细介绍如何使用Python对PDF文件中的书签进行操作... 目录简介使用工具python 向 PDF 添加书签添加书签添加嵌套书签Python 修改 PDF 书签Pytho

MySQL Workbench工具导出导入数据库方式

《MySQLWorkbench工具导出导入数据库方式》:本文主要介绍MySQLWorkbench工具导出导入数据库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录mysql Workbench工具导出导入数据库第一步 www.chinasem.cn数据库导出第二步

MyBatis分页插件PageHelper深度解析与实践指南

《MyBatis分页插件PageHelper深度解析与实践指南》在数据库操作中,分页查询是最常见的需求之一,传统的分页方式通常有两种内存分页和SQL分页,MyBatis作为优秀的ORM框架,本身并未提... 目录1. 为什么需要分页插件?2. PageHelper简介3. PageHelper集成与配置3.

一文详解如何查看本地MySQL的安装路径

《一文详解如何查看本地MySQL的安装路径》本地安装MySQL对于初学者或者开发人员来说是一项基础技能,但在安装过程中可能会遇到各种问题,:本文主要介绍如何查看本地MySQL安装路径的相关资料,需... 目录1. 如何查看本地mysql的安装路径1.1. 方法1:通过查询本地服务1.2. 方法2:通过MyS

Mysql数据库中数据的操作CRUD详解

《Mysql数据库中数据的操作CRUD详解》:本文主要介绍Mysql数据库中数据的操作(CRUD),详细描述对Mysql数据库中数据的操作(CRUD),包括插入、修改、删除数据,还有查询数据,包括... 目录一、插入数据(insert)1.插入数据的语法2.注意事项二、修改数据(update)1.语法2.有

SQL Server中的PIVOT与UNPIVOT用法具体示例详解

《SQLServer中的PIVOT与UNPIVOT用法具体示例详解》这篇文章主要给大家介绍了关于SQLServer中的PIVOT与UNPIVOT用法的具体示例,SQLServer中PIVOT和U... 目录引言一、PIVOT:将行转换为列核心作用语法结构实战示例二、UNPIVOT:将列编程转换为行核心作用语

SQL 外键Foreign Key全解析

《SQL外键ForeignKey全解析》外键是数据库表中的一列(或一组列),用于​​建立两个表之间的关联关系​​,外键的值必须匹配另一个表的主键(PrimaryKey)或唯一约束(UniqueCo... 目录1. 什么是外键?​​ ​​​​2. 外键的语法​​​​3. 外键的约束行为​​​​4. 多列外键​

MySQL精准控制Binlog日志数量的三种方案

《MySQL精准控制Binlog日志数量的三种方案》作为数据库管理员,你是否经常为服务器磁盘爆满而抓狂?Binlog就像数据库的“黑匣子”,默默记录着每一次数据变动,但若放任不管,几天内这些日志文件就... 目录 一招修改配置文件:永久生效的控制术1.定位my.cnf文件2.添加核心参数不重启热更新:高手应

关于Mybatis和JDBC的使用及区别

《关于Mybatis和JDBC的使用及区别》:本文主要介绍关于Mybatis和JDBC的使用及区别,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、JDBC1.1、流程1.2、优缺点2、MyBATis2.1、执行流程2.2、使用2.3、实现方式1、XML配置文件