1. import lombok.extern.slf4j.Slf4j;
    2. import org.apache.ibatis.cache.CacheKey;
    3. import org.apache.ibatis.executor.Executor;
    4. import org.apache.ibatis.mapping.BoundSql;
    5. import org.apache.ibatis.mapping.MappedStatement;
    6. import org.apache.ibatis.mapping.ParameterMapping;
    7. import org.apache.ibatis.plugin.Interceptor;
    8. import org.apache.ibatis.plugin.Intercepts;
    9. import org.apache.ibatis.plugin.Invocation;
    10. import org.apache.ibatis.plugin.Signature;
    11. import org.apache.ibatis.session.ResultHandler;
    12. import org.apache.ibatis.session.RowBounds;
    13. import org.springframework.stereotype.Component;
    14. import java.lang.reflect.Field;
    15. import java.util.Properties;
    16. @Slf4j
    17. @Component
    18. @Intercepts({
    19. @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
    20. })
    21. public class TenantIntercepter implements Interceptor {
    22. @Override
    23. public Object intercept(Invocation invocation) throws Throwable {
    24. Object[] args = invocation.getArgs();
    25. MappedStatement mappedStatement = (MappedStatement) args[0];
    26. Object parameterObject = args[1];
    27. RowBounds rowBounds = (RowBounds) args[2];
    28. ResultHandler resultHandler = (ResultHandler) args[3];
    29. CacheKey cacheKey = (CacheKey) args[4];
    30. BoundSql boundSql = (BoundSql) args[5];
    31. Executor executor = (Executor) invocation.getTarget();
    32. // 如果是KnowledgeFileMapper下的selectPage方法,那么就要修改参数或sql
    33. String sql = boundSql.getSql();
    34. String newSql = sql.replace("AND tenant_id = ?", "AND tenant_id in (?, ?)");
    35. // 生成新的BoundSql
    36. BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), newSql,
    37. boundSql.getParameterMappings(), boundSql.getParameterObject());
    38. // 赋值
    39. for (ParameterMapping mapping: boundSql.getParameterMappings()) {
    40. String prop = mapping.getProperty();
    41. if (boundSql.hasAdditionalParameter(prop)) {
    42. newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
    43. }
    44. }
    45. Field field = mappedStatement.getClass().getDeclaredField("boundSql");
    46. field.setAccessible(true);
    47. field.set(mappedStatement, newBoundSql);
    48. return executor.query(mappedStatement, parameterObject, rowBounds, resultHandler, cacheKey, boundSql);
    49. }
    50. @Override
    51. public Object plugin(Object target) {
    52. return Interceptor.super.plugin(target);
    53. }
    54. @Override
    55. public void setProperties(Properties properties) {
    56. Interceptor.super.setProperties(properties);
    57. }
    58. }