MyBatis Like 模糊查詢有幾種方式

2022-05-07 17:50 更新

方式1:$  這種方式,簡單,但是無法防止SQL注入,所以不推薦使用

    LIKE  '%${name}%'

方式2:#

    LIKE "%"#{name}"%"

有興趣的可以看一下:Mybatis 中#{} 和${}區(qū)別

方式3:字符串拼接

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

方式4:bind標簽

<select id="searchStudents" resultType="com.example.entity.StudentEntity"
  parameterType="com.example.entity.StudentEntity">
  <bind name="pattern1" value="'%' + _parameter.name + '%'" />
  <bind name="pattern2" value="'%' + _parameter.address + '%'" />
  SELECT * FROM test_student
  <where>
   <if test="age != null and age != '' and compare != null and compare != ''">
    age
    ${compare}
    #{age}
   </if>
   <if test="name != null and name != ''">
    AND name LIKE #{pattern1}
   </if>
   <if test="address != null and address != ''">
    AND address LIKE #{pattern2}
   </if>
  </where>
  ORDER BY id
 </select>

方式5:java代碼里寫

param.setUsername("%CD%"); 在 java 代碼中傳參的時候直接寫上

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

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號