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

相关文章

MyBatis ParameterHandler的具体使用

《MyBatisParameterHandler的具体使用》本文主要介绍了MyBatisParameterHandler的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录一、概述二、源码1 关键属性2.setParameters3.TypeHandler1.TypeHa

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

Mac电脑如何通过 IntelliJ IDEA 远程连接 MySQL

《Mac电脑如何通过IntelliJIDEA远程连接MySQL》本文详解Mac通过IntelliJIDEA远程连接MySQL的步骤,本文通过图文并茂的形式给大家介绍的非常详细,感兴趣的朋友跟... 目录MAC电脑通过 IntelliJ IDEA 远程连接 mysql 的详细教程一、前缀条件确认二、打开 ID

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十