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

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注入尽量不要使用。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容