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.Interceptor;import org.apache.ibatis.plugin.Intercepts;import org.apache.ibatis.plugin.Invocation;import org.apache.ibatis.plugin.Signature;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.springframework.stereotype.Component;import java.lang.reflect.Field;import java.util.Properties;@Slf4j@Component@Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})public class TenantIntercepter implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Object parameterObject = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; CacheKey cacheKey = (CacheKey) args[4]; BoundSql boundSql = (BoundSql) args[5]; Executor executor = (Executor) invocation.getTarget(); // 如果是KnowledgeFileMapper下的selectPage方法,那么就要修改参数或sql String sql = boundSql.getSql(); String newSql = sql.replace("AND tenant_id = ?", "AND tenant_id in (?, ?)"); // 生成新的BoundSql BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), newSql, boundSql.getParameterMappings(), boundSql.getParameterObject()); // 赋值 for (ParameterMapping mapping: boundSql.getParameterMappings()) { String prop = mapping.getProperty(); if (boundSql.hasAdditionalParameter(prop)) { newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop)); } } Field field = mappedStatement.getClass().getDeclaredField("boundSql"); field.setAccessible(true); field.set(mappedStatement, newBoundSql); return executor.query(mappedStatement, parameterObject, rowBounds, resultHandler, cacheKey, boundSql); } @Override public Object plugin(Object target) { return Interceptor.super.plugin(target); } @Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); }}