MyBatis Plus之like模糊查询中包含有特殊字符(_、\、%)

传统的解决思路:自定义一个拦截器,当有模糊查询时,模糊查询的关键字中包含有上述特殊字符时,在该特殊字符前添加\进行转义处理。

新的解决思路:将like 替换为 MySQL内置函数locate函数

一、问题提出

使用MyBatis中的模糊查询时,当查询关键字中包括有_\%时,查询关键字失效。

二、问题分析

1、当like中包含_时,查询仍为全部,即 like ‘%_%‘查询出来的结果与like ‘%%‘一致,并不能查询出实际字段中包含有_特殊字符的结果条目
2、like中包括%时,与1中相同
3、like中包含\时,带入查询时,%\%无法查询到包含字段中有\的条目

特殊字符 未处理 处理后
_ like ‘%_%‘ like ‘%\_%‘
% like ‘%%%‘ like ‘%\%%‘
\ like ‘%\%‘ `like ‘%\%‘
  • ESCAPE ‘/‘必须加在SQL的最后。
  • like ‘%\_%‘效果与like concat(‘%‘, ‘\_‘, ‘%‘)相同

三、问题解决

1、自定义拦截器方法类



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keyidea.boss.utils.EscapeUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * 自定义拦截器方法,处理模糊查询中包含特殊字符(_、%、\)
 */
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
    RowBounds.class, ResultHandler.class}))
public class MyInterceptor implements Interceptor {

    Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截sql
        Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement)args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        String sql = boundSql.getSql();
        // 处理特殊字符
        modifyLikeSql(sql, parameterObject, boundSql);
        // 返回
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {

    }

    @SuppressWarnings("unchecked")
    public static String modifyLikeSql(String sql, Object parameterObject, BoundSql boundSql) {
        if (parameterObject instanceof HashMap) {
        } else {
            return sql;
        }
        if (!sql.toLowerCase().contains(" like ") || !sql.toLowerCase().contains("?")) {
            return sql;
        }
        // 获取关键字的个数(去重)
        String[] strList = sql.split("\\?");
        Set<String> keyNames = new HashSet<>();
        for (int i = 0; i < strList.length; i++) {
            if (strList[i].toLowerCase().contains(" like ")) {
                String keyName = boundSql.getParameterMappings().get(i).getProperty();
                keyNames.add(keyName);
            }
        }
        // 对关键字进行特殊字符“清洗”,如果有特殊字符的,在特殊字符前添加转义字符(\)
        for (String keyName : keyNames) {
            HashMap parameter = (HashMap)parameterObject;
            if (keyName.contains("ew.paramNameValuePairs.") && sql.toLowerCase().contains(" like ?")) {
                // 第一种情况:在业务层进行条件构造产生的模糊查询关键字
                QueryWrapper wrapper = (QueryWrapper)parameter.get("ew");
                parameter = (HashMap)wrapper.getParamNameValuePairs();

                String[] keyList = keyName.split("\\.");
                // ew.paramNameValuePairs.MPGENVAL1,截取字符串之后,获取第三个,即为参数名
                Object a = parameter.get(keyList[2]);
                if (a instanceof String && (a.toString().contains("_") || a.toString().contains("\\") || a.toString()
                    .contains("%"))) {
                    parameter.put(keyList[2],
                        "%" + EscapeUtil.escapeChar(a.toString().substring(1, a.toString().length() - 1)) + "%");
                }
            } else if (!keyName.contains("ew.paramNameValuePairs.") && sql.toLowerCase().contains(" like ?")) {
                // 第二种情况:未使用条件构造器,但是在service层进行了查询关键字与模糊查询符`%`手动拼接
                Object a = parameter.get(keyName);
                if (a instanceof String && (a.toString().contains("_") || a.toString().contains("\\") || a.toString()
                    .contains("%"))) {
                    parameter.put(keyName,
                        "%" + EscapeUtil.escapeChar(a.toString().substring(1, a.toString().length() - 1)) + "%");
                }
            } else {
                // 第三种情况:在Mapper类的注解SQL中进行了模糊查询的拼接
                Object a = parameter.get(keyName);
                if (a instanceof String && (a.toString().contains("_") || a.toString().contains("\\") || a.toString()
                    .contains("%"))) {
                    parameter.put(keyName, EscapeUtil.escapeChar(a.toString()));
                }
            }
        }
        return sql;
    }
}

2、在配置类中添加自定义拦截器



import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * MyBatis配置数据源、sqlSessionFactory、事务管理器、分页插件、自定义拦截器等
 */
@Configuration
@MapperScan(basePackages = {"com.keyidea.boss.mapper"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MybatisPlusConfig {

    @Autowired
    private MybatisPlusProperties properties;
    // 使用MyBatis中的分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        return page;
    }
    // 自定义拦截器实现模糊查询中的特殊字符处理
    @Bean
    public MyInterceptor myInterceptor() {
        MyInterceptor sql = new MyInterceptor();
        return sql;
    }
    // 数据源配置
    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource")
    @Primary
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
    // 配置sqlSessionFactory
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource,
        PaginationInterceptor paginationInterceptor, MyInterceptor myInterceptor) throws Exception {
        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();

        sessionFactory.setDataSource(dataSource);

        if (this.properties.getConfigurationProperties() != null) {
            sessionFactory.setConfigurationProperties(this.properties.getConfigurationProperties());
        }
        GlobalConfig globalConfig = this.properties.getGlobalConfig();
        sessionFactory.setGlobalConfig(globalConfig);

        // 设置MyBatis的插件/拦截器列表
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(paginationInterceptor);
        interceptors.add(myInterceptor);
        sessionFactory.setPlugins(interceptors.toArray(new Interceptor[1]));

        return sessionFactory.getObject();
    }
    // 设置事务管理器,在需要事务的service层使用如下注解进行事务管理
    // @Transactional(transactionManager = "masterTransactionManager", rollbackFor = Exception.class)
    @Bean(name = "masterTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
  • 由于框架中使用多个数据源配置,因此使用数据库事务时,优先使用该事务时,需要在该方法上显著的添加@Primary注解

3、工具类:特殊字符转义

import org.apache.commons.lang3.StringUtils;

public class EscapeUtil {
    //mysql的模糊查询时特殊字符转义
    public static String escapeChar(String before){
        if(StringUtils.isNotBlank(before)){
            before = before.replaceAll("\\\\", "\\\\\\\\");
            before = before.replaceAll("_", "\\\\_");
            before = before.replaceAll("%", "\\\\%");
        }
        return before ;
    }
}

4、引入依赖包,以下为参考项

build.gradle文件中的依赖如下

dependencies {
    implementation ‘org.springframework.boot:spring-boot-starter-web‘
    testImplementation ‘org.springframework.boot:spring-boot-starter-test‘
    implementation ‘org.springframework.boot:spring-boot-starter-aop‘
    implementation ‘com.baomidou:mybatis-plus-boot-starter:3.1.0‘
    implementation ‘com.alibaba:druid-spring-boot-starter:1.1.10‘
    implementation ‘mysql:mysql-connector-java‘
    implementation ‘org.apache.commons:commons-lang3:3.4‘
    implementation ‘org.jeecg:easypoi-base:2.1.3‘
    implementation ‘org.jeecg:easypoi-annotation:2.1.3‘
    implementation ‘org.springframework.boot:spring-boot-starter-mail‘
    compile ‘org.apache.httpcomponents:httpclient:4.3.1‘
    compile ‘net.sf.json-lib:json-lib:2.4:jdk15‘
}

四、重点关注

以上方法在关键字中包含有\可能会失效,失效的原因是由于查询的关键字的数据库字段排序规则为utf8_unicode_ci,如下图

字段排序规则为:utf8_unicode_ci

要想不失效,查询的关键字的排序规则必须为utf8_general_ci,如下图

字段排序规则为:utf8_general_ci

或者统一全部数据库字符集与排序规则分别为:utf8mb4utf8mb4_general_ci,如下图

字段排序规则为:utf8mb4_general_ci

【END】

原文地址:https://www.cnblogs.com/haoyul/p/11687728.html

时间: 2024-08-28 12:29:36

MyBatis Plus之like模糊查询中包含有特殊字符(_、\、%)的相关文章

spring boot中mybatis使用注解进行模糊查询

小白一枚,spring boot 2.0.5在使用mybatis进行注解模糊查询时遇到一些低级的错误,现记录下来错误示例:"select * from user where name like \""#{name}\""这个错误报Parameter index out of range (1 > number of parameters, which is 0): 经过百度查询其它的得到这条sql语句,虽然能查出来,但是是全部数据都查出来了"

【Mybatis】【3】mybatis Example Criteria like 模糊查询

正文: 在Java中使用Mybatis自动生成的方法,like需要自己写通配符 public List<TableA> query(String name) { Example example = new Example(TableA.class); example.createCriteria() .andLike("name", "%"+ name +"%"); example.setOrderByClause("CRE

模糊查询中输入通配符的问题

模糊查询中输入通配符的问题: 比如说在搜索框中输入'%'.'_'.'/'时会出错,因为这些特殊符号在sql语句查询的时候是有他特定的意义的,所有这里要对前台传过来的keyword搜索内容进行排除通配符处理,我是在工具类中写了一个方法代码如下: /*** 根据搜索特殊字符串* @param id* @return 取不到返回null*/public static String specialStr(String str){Integer index=str.indexOf("%");In

mybatis中llike模糊查询中#和$的使用,以及bind标签的使用

关于#{}和${}就是jdbc中的预编译和非预编译 1.表达式: name like"%"#{name}"%" 打印的日志 ==>  Preparing: select * from user WHERE name like"%"?"%" ==>Parameters: 傻(String), 1(Integer) 能够查询出来,没有问题,这是使用了占位符来占位,写成SQL就是: name like "%&q

MySQL模糊查询中通配符的转义

sql中经常用like进行模糊查询,而模糊查询就要用到百分号“%”,下划线“_”这些通配符,其中“%”匹配任意多个字符,“_”匹配单个字符. 如果我们想要模糊查询带有通配符的字符串,如“60%”,“user_name”,就需要对通配符进行转义.如下,斜杠后面的%就不再是通配符,斜杠之前的%仍然起通配符作用. select percent from score where percent like '%0/%' escape '/';

mybatis自定义join和模糊查询

关于mybatis通过和数据库连接生成的map.xml不能满足我们的查询条件的时候,我们要做的就是自定义一个查询的功能. (1)需要在生成的xml文件当中添加我们想要join的两张表的字段信息. <resultMap id="queryForListMap" type="com.report.pojo.RuleRunResult"> <id column="INTERNAL_ID" property="internal

子查询中包含不存在的列--居然不是bug!

1.现象 create table a as (select 1 as col_a); create table b as (select 2 as col_b)  select *  from a  where col_a in (select col_a from b) 其中,col_a只存在于table_a中,table_b中没有该字段,整条语句的结果是可以成功执行! 2.原因: 这个问题比较困惑,网上搜到的原因是"当子查询中的列名不存在时,自动向外层寻找". 也就是说,上面的查

关于mybatis中llike模糊查询中#和$的使用

在mybatis中经常要写到like 查询,以前从来没有遇到什么问题,突然遇到一个问题,找了好长时间没找到,最后找到了,是关于#和$的使用的,总结如下: name like  表达式    and    falg=#{falg} 本次示例中共两个条件,一个是name  like  表达式, 还有flag相等,这个是使用#{}占位符,没有任何问题,关键问题就是 表达式的书写.下面来研究下表达式的书写: 如果写成'%#{name}%' ,就会报错Parameter index out of rang

MyBatis动态SQL与模糊查询

sqlxml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="PersonCondition"&