Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MyBatis Like fuzzy queries come in several ways


May 16, 2021 MyBatis



Mode 1:$ this way, simple, but can not prevent SQL injection, so it is not recommended to use

LIKE '%${name}%'

Mode 2: #

LIKE "%"#{name}"%"

Interested to see: The difference between the ones in Mybatis is the same as the one in the "

Mode 3: String stitching

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

Mode 4: Bind label

  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>

Mode 5: written in java code

param.setUsername("%CD%"); Write directly when passing on a ginseng in java code

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

Then mapper writes directly in the . . .