Mybatis模糊查询的三种写法

Mybatis中LIKE的三种写法

第一种写法:

复制代码
 <select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
          personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                "%${personName,jdbcType=VARCHAR}%"
            </if>
        </where>
    </select>
复制代码

$符号可能导致SQL注入,不推荐。因为#{}是预编译处理,${}是字符串替换,Mybatis在处理#{}时,会将SQL中的#{}替换为?,

调用PreparedStatement的set方法来赋值;Mybatis在处理${}时,就是把${}替换成变量的值。

第二种写法:

复制代码
<select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
          personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                "%"#{personName,jdbcType=VARCHAR}"%"
            </if>
        </where>
    </select>
复制代码

#{}在解析sql语句时候,在变量外侧自动加单引号'  ',因此这里 % 需要使用双引号"  ",不能使用单引号 '  ',否则会查不到任何结果。

第三种写法

复制代码
<select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
        personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                CONCAT('%', #{personName,jdbcType=VARCHAR}, '%')
            </if>
        </where>
    </select>
复制代码

 使用CONCAT()函数连接参数形式,推荐使用这种方法。

posted @   北国浪子  阅读(2443)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示