Java web

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

2021-03-18  本文已影响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注入尽量不要使用。

上一篇 下一篇

猜你喜欢

热点阅读