在mybatis中拼接查詢語句,偶爾會出現where后面可能一個字段的值都沒有,就導致所有條件無效,導致where沒有存在的意義;但也有可能這些條件會存在。那解決這個問題的方法,最常見的就是:
在where后面添加1=1
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE 1=1 <if test="state != null"> and state = #{state} </if> </select>
但是這種做法有一個最大的弊端,就是導致數據表上的索引失效,如果有索引的話。而且還是一個垃圾條件
所以正確的做法應該是:
使用<where>標簽 解決這個問題
where標簽會自動處理第一個為null時候的and問題
<select id="findUiImage4Map" parameterType="com.pisen.cloud.luna.ms.ten.ui.config.base.domain.UiImage" resultType="java.util.HashMap"> select uid, imgUrl from ui_image uii <where> <if test="imgType != null and imgType != '' "> AND uii.img_type = #{imgType} </if> <if test="uploadDate != null and uploadDate != '' "> AND DATE_FORMAT(uii.upload_date,'%Y-%m-%d') = DATE_FORMAT(#{uploadDate},'%Y-%m-%d') </if> </where> </select>