mybatis避免Where 空條件的尷尬
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
</select>
如果state引數為空時,最終生成SQL語句為
SELECT * FROM BLOG
WHERE
執行會出錯,當然,你可以在where 後加一個1=1,改成
但是這個做法不太“環保”(畢竟引入了一個垃圾條件),其實只要改成<where>...</where>即可<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE 1=1 <if test="state != null"> and state = #{state} </if> </select>
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
and state = #{state}
</if>
</where>
</select>