MyBatis Like 模糊查询有几种方式

方式1:$  这种方式,简单,但是无法防止SQL注入,所以不推荐使用

    LIKE  %${name}%

方式2:#

    LIKE “%”#{name}”%”

有兴趣的可以看一下:Mybatis 中#{} 和${}区别

方式3:字符串拼接

AND name LIKE CONCAT(CONCAT(%,#{name},%))

方式4:bind标签

  1. <select id="searchStudents" resultType="com.example.entity.StudentEntity"
  2. parameterType="com.example.entity.StudentEntity">
  3. <bind name="pattern1" value="% + _parameter.name + %" />
  4. <bind name="pattern2" value="% + _parameter.address + %" />
  5. SELECT * FROM test_student
  6. <where>
  7. <if test="age != null and age != and compare != null and compare != ">
  8. age
  9. ${compare}
  10. #{age}
  11. </if>
  12. <if test="name != null and name != ">
  13. AND name LIKE #{pattern1}
  14. </if>
  15. <if test="address != null and address != ">
  16. AND address LIKE #{pattern2}
  17. </if>
  18. </where>
  19. ORDER BY id
  20. </select>

方式5:java代码里写

param.setUsername(“%CD%”); 在 java 代码中传参的时候直接写上

           <if test="username!=null"> AND username LIKE #{username}</if>

然后 mapper 里面直接写 #{} 就可以了

作者:admin,如若转载,请注明出处:https://www.web176.com/mybatis/12530.html

(0)
打赏 支付宝 支付宝 微信 微信
adminadmin
上一篇 2023年3月8日
下一篇 2023年3月8日

相关推荐

发表回复

登录后才能评论