1. 程式人生 > 其它 >mybatis使用<choose> <when>

mybatis使用<choose> <when>

一、需求

後臺使用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。