Mybatis的xml中使用if/else標(biāo)簽的具體使用
使用if標(biāo)簽進(jìn)行查詢
SELECT
orderNo,
adname,
orderstatus
FROM
order_A
where
<if test="order!=null">
order=#{order}
</if>
<if test="title!=null">
and title=#{title}
</if>
需要注意的是:如果第一個(gè)if的order為null的話 第二值title也為null的話運(yùn)行會(huì)報(bào)錯(cuò),就算第一個(gè)if等于null 那么查詢語(yǔ)句變成 where and title='哈哈哈' 這樣運(yùn)行的話也會(huì)出現(xiàn)錯(cuò)誤。
where標(biāo)簽出場(chǎng)
SELECT
orderNo,
adname,
orderstatus
FROM
order_A
<where>
<if test="order!=null">
order=#{order}
</if>
<if test="order!=null">
and title=#{title}
</if>
</where>
where 元素只會(huì)在至少有一個(gè)子元素的條件返回 SQL 子句的情況下才去插入WHERE子句。而且,若語(yǔ)句的開頭為AND或OR,where 元素也會(huì)將它們?nèi)コ_@個(gè)只能解決2個(gè)值都為空。
不能解決order值為空但是title值為空時(shí)還是會(huì)出現(xiàn)語(yǔ)句錯(cuò)誤的情況,這個(gè)時(shí)候我們可以在and 前面用1=1或者true來(lái)解決
如:

或這樣

if/else 使用 choose,when,otherwise 代替
由于Mybatis中沒有else標(biāo)簽但是可以通過(guò)choose,when,otherwise來(lái)使用
SELECT orderNo, adname, orderstatus FROM <choose> <when test=" platformtype != null and platformtype.trim() != '' and platformtype == 1"> `orders_A` as orderTable </when> <when test=" platformtype != null and platformtype.trim() != '' and platformtype == 2"> `orders_B` as orderTable </when> <when test=" platformtype != null and platformtype.trim() != '' and platformtype == 3"> `orders_C` as orderTable </when> <otherwise> `orders_A` as orderTable </otherwise> </choose>
翻譯一下上面的語(yǔ)句:
當(dāng)platformtype 值不為空并且把platformtype 值進(jìn)行去除空字符串,并且值等于1時(shí)
就會(huì)把表orders_A進(jìn)行拼接,如果條件都不符合的話就會(huì)走otherwise標(biāo)簽?zāi)J(rèn)拼接orders_A表進(jìn)行查詢
choose,when,otherwise標(biāo)簽有點(diǎn)像Java中的switch 當(dāng)where的test值滿足時(shí)會(huì)拼接里面的表,otherwise表示其他when標(biāo)簽都不滿足時(shí)執(zhí)行拼接
到此這篇關(guān)于Mybatis的xml中使用if/else標(biāo)簽的具體使用的文章就介紹到這了,更多相關(guān)Mybatis xml=使用if/else標(biāo)簽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot項(xiàng)目中使用騰訊云發(fā)送短信的實(shí)現(xiàn)
本文主要介紹了SpringBoot項(xiàng)目中使用騰訊云發(fā)送短信的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(30)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07

