Mybatis choose元素的用法
項目遇到一個需求,需要實現動態 or 條件查詢, 已知動態 and 查詢使用 <if>元素,查詢了官網,<choose>元素剛好能滿足動態 or需求。
choose 介紹
有時候,我們不需要使用到所有的條件,只要滿足其中的一個條件即可。<choose>元素為此而生,它類似 Java 的 switch 語句,具有高度的相似性。choose元素就好比 switch在最外層,<choose>元素下還有<when>及<otherwise>兩個元素,<when>元素類似於case,而<otherwise>則類似於default。
官網相關介紹:https://mybatis.org/mybatis-3/zh/dynamic-sql.html
choose 例子
<select id="selectCount" resultType="java.lang.Integer">
SELECT COUNT(*)
FROM
project_development pd
LEFT JOIN business_customer bc ON bc.id = pd.customer_id
LEFT JOIN base_project bp ON bp.id = pd.project_id
WHERE
pd.WORK = 1
<if test="id != null">
and pd.id = #{id}
</if>
<choose>
<when test="sort != null">
order by pd.sort desc,pd.name
</when>
<otherwise>
order by pd.start_date desc,pd.status desc,pd.progress desc,pd.id desc
</otherwise>
</choose>
</select>
當 sort參數不為空時,執行 <when>元素下的排序,<when>元素可以同時存在多個,滿足其中一個條件時就執行相應的sql,然后跳出<choose>,當所有<when>都不滿足時,則執行<otherwise>下的sql。
<choose>元素的應用還是比較簡單的,這里就不多贅述。
