项目场景:

springboot项目中需要实现忽略大小写的模糊查询,底层数据库为pgsql

场景分析:

项目集成了mybatis,模糊查询一般使用like关键字,且pgsql本身提供ilike关键字实现忽略大小写的模糊匹配,因此可以考虑采用mybatis的拦截器,对特定sql进行修改。

解决方案:

package com.xxx;

import lombok.extern.slf4j.Slf4j;
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.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * sql查询拦截器
 * <p>
 * 模糊查询时忽略大小写
 * </p>
 * @author lsh
 * @version 1.0
 * @date 2022/5/10 11:13
 */
@Slf4j
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class FuzzyQueryInterceptor implements Interceptor{
    private static final String FUZZY_QUERY_KEY = "like";
    private static final String IGNORE_FUZZY_QUERY_KEY = "ilike";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //拦截StatementHandler,获取Mybatis对象属性
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = MetaObject
                .forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
                        new DefaultReflectorFactory());
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        //执行mapper方法的全路径名
        String id = mappedStatement.getId();
        //只拦截查询语句,将like关键字替换成ilike,以忽略大小写
        if (SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())){
            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql();
            if (sql.contains(FUZZY_QUERY_KEY) || sql.contains(FUZZY_QUERY_KEY.toUpperCase())){
                String mSql = sql.contains(FUZZY_QUERY_KEY) ? sql.replace(FUZZY_QUERY_KEY,IGNORE_FUZZY_QUERY_KEY)
                        : sql.replace(FUZZY_QUERY_KEY.toUpperCase(),IGNORE_FUZZY_QUERY_KEY.toUpperCase());
                log.debug(id + ":原始查询语句 ==> " + sql);
                log.debug(id + ":替换后的查询语句 ==> " + mSql);
                //通过反射修改sql语句
                Field field = boundSql.getClass().getDeclaredField("sql");
                field.setAccessible(true);
                field.set(boundSql, mSql);
            }
        }
        //执行结果
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐