為什么在動態SQL中where條件判斷的時候后面跟上and不會報錯


假如現在我們要查詢一個姓張的且名字大於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 &gt; #{age}
</if>
</where>
接口中的寫法

public List findUsersByName(@Param(“name”) String name, @Param(“age”) Integer age);

如果一個人的姓名為空的話,第一個if語句就不會執行,但是后面的if語句成立的話,會形成
select * from user where and age &gt; #{age},這種sql語句在執行過程中是會報錯的,但是實際運行時卻沒有報錯,sql語句變成了select id, name, age from user where ? like concat (?, ‘%’) ,and不見了?,為什么,且在沒有名字的情況下記錄User [id=4, name=, age=26]也被查了出來,在查閱了各種資料之后,才知道,如果標簽返回的內容是以AND 或OR 開頭的,where語句會將多余的and或or剔除掉。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM