mybatis使用


一、需求

   后台使用orcale數據庫,mybatis做持久層,前台搜索功能,根據類型搜索,但是數據庫中沒有類型字段,

   所以需要在where條件語句中進行判斷,當type == x1 時和type == x2時where中的判斷條件不同

二、解決

<select id = "" resultMap = "">

   select * from table

   <where>

          <if test="type == 'x1' ">

               and  條件1;

         </if>

        <if test="type == 'x2' ">

               and  條件2;

         </if>

   </where>

</select>

或者

<select id = "" resultMap = "">

  select * from table

   <choose>

          <when test=" type == 'x1' '">

              where   條件1;

         </when >

         <when test=" type == 'x2' '">

              where  條件2;

         </when 

        <otherwise>

               條件3;   // 可以為空

       </otherwise>

 

   </choose>

    <if test="type == 'x2' ">   //如果除了以上條件外還有判斷的條件,放在chose標簽外,不用再寫where

               and  條件2;

    </if>

</select>

再或者

 

<select id = "" resultMap = "">

 

  select * from table

  <where>

 

   <choose>

 

          <when test=" type == 'x1' '">

 

                  條件1;

 

         </when >

 

         <when test=" type == 'x2' '">

 

                條件2;

 

         </when > 

 

        <otherwise>

 

               條件3;   // 可以為空

 

       </otherwise>

 

   </choose>

 

    <if test="type == 'x2' ">   //如果除了以上條件外還有判斷的條件,放在chose標簽外,不用再寫where

 

               and  條件2;

 

    </if>

  </where>

 

</select>

 

choose標簽是按順序判斷其內部when標簽中的test條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的sql。


免責聲明!

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



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