Mybatis模糊查询之# $差别

Studnet类如下:

在这里插入图片描述

现在根据电话模糊查询员工

方式一:

<select id="getStudentByPhoneLike" resultType="student">
        select
        <include refid="all_columns"></include>
        from
             student
        where
              phone like #{phone}
</select>

测试:

手动添加 %通配符进行模糊查询
在这里插入图片描述
在这里插入图片描述
方式二:

<select id="getStudentByPhoneLike" resultType="student">
        select
        <include refid="all_columns"></include>
        from
             student
        where
              phone like '${phone}%'
</select>

测试:

在这里插入图片描述
在这里插入图片描述
方式三:

使用 # ,同时用户不再手动输入通配符。
既方便了用户操作,同时又防止sql注入问题。

<select id="getStudentByPhoneLike" resultType="student">
        select
        <include refid="all_columns"></include>
        from
             student
        where
              phone like concat('%',#{phone},'%')
</select>

方式四:

<select id="getStudentByPhoneLike" resultType="student">
        select
        <include refid="all_columns"></include>
        from
             student
        where
              phone like concat('%','${phone}','%')
</select>

总结:

#{ }是预编译处理,MyBatis在处理#{ }时,它会将sql中的#{ }替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,使用占位符的方式提高效率,可以防止sql注入。
${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,可能引发sql注入。

文章学习原文地址


版权声明:本文为ACMjiayou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。