Mybatis choose (when, otherwise)標籤

choose標籤是按順序判斷其內部when標籤中的test條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的sql。類似於Java 的 switch 語句,choose 爲 switch,when 爲 case,otherwise 則爲 default。

例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。choose會從上到下選擇一個when標籤的test爲true的sql執行。安全考慮,我們使用where將choose包起來,放置關鍵字多於錯誤。

<!--  choose(判斷參數) - 按順序將實體類 User 第一個不爲空的屬性作爲:where條件 -->  
<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
            </when >  
            <when test="sex != null and sex != '' ">  
                AND u.sex = #{sex, jdbcType=INTEGER}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday, jdbcType=DATE}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>

發佈了18 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章