2 MyBatis動態sql之where標簽|轉


1 MyBatis動態SQL之if 語句
2 MyBatis動態sql之where標簽|轉
3 MyBatis動態SQL之set標簽|轉
4 MyBatis動態SQL之trim元素|轉
5 MyBatis動態sql中foreach標簽的使用
6 MyBatis動態SQL之choose(when、otherwise)語句
7 MyBatis動態SQL之bind標簽|轉

  where標簽的作用類似於動態sql中的set標簽,主要用來簡化sql語句中where條件,使得MyBatis 自動判斷是否需要加where語句,並且避免在查詢條件開頭強制添加類似WHERE state = 'ACTIVE'語句之后,才可以添加if標簽。

  使用案例如下所示:

   <select id="selectByParams" parameterType="map" resultType="user">
    select * from user
    <where>
      <if test="id != null ">and id=#{id}</if>
      <if test="name != null and name.length()>0" >and name=#{name}</if>
      <if test="gender != null and gender.length()>0">and gender = #{gender}</if>
            and state = 'ACTIVE'
    </where>
   </select>

  案例解析:按照標准寫法,第一個 標簽內應該不寫 and,但是,即便寫了 and也不會報錯,因為where標簽自動地幫助我們移除了第一個 and關鍵字。溫馨提示,第二個之后的 標簽內,必須有 and 關鍵字。

  where標簽只有在一個以上的if條件有值的情況下,才去主動添加WHERE子句。而且,若緊鄰where關鍵字的內容是“AND”或“OR”開頭,則where標簽自動把它們去除。例如,在上述SQL中,如果只有查詢條件id的值為null,那么控制台打印出來的SQL為:

select * from user where name="xx" and gender="yy";


免責聲明!

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



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