假如現在我們要查詢一個姓張的且名字大於25的人:
xml中的寫法
select <include refid="userCols" /> from user
<where>
<if test="name != null and name != ''">
and name like concat(#{name}, '%')
</if>
<if test="age != null and age != ''">
and age > #{age}
</if>
</where>
接口中的寫法
public List findUsersByName(@Param(“name”) String name, @Param(“age”) Integer age);
如果一個人的姓名為空的話,第一個if語句就不會執行,但是后面的if語句成立的話,會形成
select * from user where and age >; #{age},這種sql語句在執行過程中是會報錯的,但是實際運行時卻沒有報錯,sql語句變成了select id, name, age from user where ? like concat (?, ‘%’) ,and不見了?,為什么,且在沒有名字的情況下記錄User [id=4, name=, age=26]也被查了出來,在查閱了各種資料之后,才知道,如果標簽返回的內容是以AND 或OR 開頭的,where語句會將多余的and或or剔除掉。