美文网首页Java web
Mybatis模糊查询的几种书写格式

Mybatis模糊查询的几种书写格式

作者: 勿念及时雨 | 来源:发表于2021-03-18 09:07 被阅读0次

Mybatis中使用like进行模糊查询,主要有三种书写格式。

格式一:使用'%${...}%'

示例:

<select id = "findUserInfo" parameterType="UserInfo" resultType="UserInfo">
  select * from user_info 
  <where>
    <if test="userName != null">
      and user_name like '%${userName}%'
    </if>
    <if test="userRole != null">
      and user_role like '%${userRole}%'
    </if>
  </where>
</select>

由于$是直接注入参数,这种写法不能注明jdbcType,同时这种写法也可能引起SQL注入,尽量避免使用这种写法。

格式二:使用"%"#{...}"%"

示例:

<select id = "findUserInfo" parameterType="UserInfo" resultType="UserInfo">
  select * from user_info 
  <where>
    <if test="userName != null">
      and user_name like "%"#{userName,jdbcType=VARCHAR}"%"
    </if>
    <if test="userRole != null">
      and user_role like "%"#{userRole,jdbcType=VARCHAR}"%"
    </if>
  </where>
</select>

由于#{...}解析为SQL时会在变量外侧自动加单引号'',所以这里的%需要使用"",不能使用''。

格式三:使用CONCAT()函数连接参数

示例:

<select id = "findUserInfo" parameterType="UserInfo" resultType="UserInfo">
  select * from user_info 
  <where>
    <if test="userName != null">
      and user_name like CONCAT('%',#{userName,jdbcType=VARCHAR},'%')
    </if>
    <if test="userRole != null">
      and user_role like CONCAT('%',#{userRole,jdbcType=VARCHAR},'%')
    </if>
  </where>
</select>

总结

上述三种书写格式,推荐使用格式二和格式三,格式一因为容易引起SQL注入尽量不要使用。

相关文章

网友评论

    本文标题:Mybatis模糊查询的几种书写格式

    本文链接:https://www.haomeiwen.com/subject/ykeecltx.html