方式1:$ 這種方式,簡(jiǎn)單,但是無(wú)法防止SQL注入,所以不推薦使用
LIKE '%${name}%'
方式2:#
LIKE "%"#{name}"%"
有興趣的可以看一下:Mybatis 中#{} 和${}區(qū)別
方式3:字符串拼接
AND name LIKE CONCAT(CONCAT('%',#{name},'%'))
方式4:bind標(biāo)簽
<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代碼里寫(xiě)
param.setUsername("%CD%"); 在 java 代碼中傳參的時(shí)候直接寫(xiě)上
<if test="username!=null"> AND username LIKE #{username}</if>
然后 mapper 里面直接寫(xiě) #{} 就可以了
更多建議: