1. 程式人生 > >Mybatis動態SQL--choose when

Mybatis動態SQL--choose when

參考MyBatis choose(when, otherwise)標籤

前言:

使用mybatis操作資料庫肯定是需要自己書寫SQL語句的,這在帶來方便(進行SQL優化/定製)的同時也要求我們對mybatis的動態SQL有一定了解.

例如在where子句中進行判斷,有時候我們並不想應用所有的條件,而只是想根據現有條件從多個選項中選擇一個判斷條件(邏輯或的關係)。而使用if標籤時,只要test中的表示式為 true,就會執行 if 標籤中的條件(多個if條件之間是邏輯與的關係)。MyBatis 提供了 choose 元素,choose標籤是按順序判斷其內部when標籤中的test條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的sql。類似於Java 的 switch 語句,choose 為 switch,when 為 case,otherwise 則為 default。

栗子

<select id="demoMapper" resultType="java.util.hashMap" parameterType="java.util.hashMap">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  //CONCAT字串連線函式用於連線兩個字串
            </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>  

上述的動態SQL相當於:若username不為null

SELECT * FROM User u where u.username LIKE ('%'+?+'%');

若色系不為null或空串

SELECT * FROM User u where u.sex = ?;

若上述兩個條件都不滿足

SELECT * FROM User u