有時(shí)候我們并不想應(yīng)用所有的條件,而只是想從多個(gè)選項(xiàng)中選擇一個(gè)只泼。而使用if標(biāo)簽時(shí)剖笙,只要test中的表達(dá)式為 true,就會(huì)執(zhí)行 if 標(biāo)簽中的條件请唱。MyBatis 提供了 choose 元素弥咪。if標(biāo)簽是與(and)的關(guān)系,而 choose 是或(or)的關(guān)系十绑。
choose標(biāo)簽是按順序判斷其內(nèi)部when標(biāo)簽中的test條件出否成立聚至,如果有一個(gè)成立,則 choose 結(jié)束本橙。當(dāng) choose 中所有 when 的條件都不滿則時(shí)扳躬,則執(zhí)行 otherwise 中的sql。類似于Java 的 switch 語句甚亭,choose 為 switch,when 為 case,otherwise 則為 default苔严。
例如下面例子每瞒,同樣把所有可以限制的條件都寫上,方面使用暇唾。choose會(huì)從上到下選擇一個(gè)when標(biāo)簽的test為true的sql執(zhí)行促脉。安全考慮啰挪,我們使用where將choose包起來,放置關(guān)鍵字多于錯(cuò)誤嘲叔。
<!-- choose(判斷參數(shù)) - 按順序?qū)?shí)體類 User 第一個(gè)不為空的屬性作為: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>
choose (when,otherwize) ,相當(dāng)于java 語言中的 switch ,與 jstl 中 的 choose 很類似亡呵。
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
and content = #{content}
</when>
<otherwise>
and owner = "owner1"
</otherwise>
</choose>
</select>
when元素表示當(dāng) when 中的條件滿足的時(shí)候就輸出其中的內(nèi)容,跟 JAVA 中的 switch 效果差不多的是按照條件的順序硫戈,當(dāng) when 中有條件滿足的時(shí)候锰什,就會(huì)跳出 choose,即所有的 when 和 otherwise 條件中丁逝,只有一個(gè)會(huì)輸出汁胆,當(dāng)所有的我很條件都不滿足的時(shí)候就輸出 otherwise 中的內(nèi)容。所以上述語句的意思非常簡單霜幼, 當(dāng) title!=null 的時(shí)候就輸出 and titlte = #{title}嫩码,不再往下判斷條件,當(dāng)title為空且 content!=null 的時(shí)候就輸出 and content = #{content}罪既,當(dāng)所有條件都不滿足的時(shí)候就輸出 otherwise 中的內(nèi)容铸题。