Mybatis模糊查询结果为空的解决方案

写在前面

Mybatis使用模糊查询,查询结果为空的解决方案,我的代码是

select * from sp_user where 1=1
<if test="username!=null">
    and username like '%'#{username}'%'
</if>

查询结果如下:

2021-05-14 23:45:20.078 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : ==>  Preparing: select * from sp_user where 1=1 and username like '%'?'%'
2021-05-14 23:45:20.105 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : ==> Parameters: ad(String)
2021-05-14 23:45:20.130 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : <==      Total: 0

解决方案

百度了很多,都说在数据库的url上添加useUnicode=true&characterEncoding=utf-8
我加了,结果还是查询不到,后来试了一下CONTACT函数

        select * from sp_user where 1=1
        <if test="username!=null">
            and username like CONCAT('%',#{username},'%')
        </if>

查询结果如下:

2021-05-14 23:45:20.078 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : ==>  Preparing: select * from sp_user where 1=1 and username like CONCAT('%',?,'%') 
2021-05-14 23:45:20.105 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : ==> Parameters: ad(String)
2021-05-14 23:45:20.130 DEBUG 15620 --- [           main] c.e.s.mapper.UserMapper.selectByQuery    : <==      Total: 1

我用的mybatis版本是:

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

希望结果对大家有用~ 共勉!

原文地址:https://www.cnblogs.com/Fzeng/p/14770582.html