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>
需要注意的是:如果第一個if的order為null的話 第二值title也為null的話運(yùn)行會報錯,就算第一個if等于null 那么查詢語句變成 where and title='哈哈哈' 這樣運(yùn)行的話也會出現(xiàn)錯誤。
where標(biāo)簽出場
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 元素只會在至少有一個子元素的條件返回 SQL 子句的情況下才去插入WHERE子句。而且,若語句的開頭為AND或OR,where 元素也會將它們?nèi)コ?。這個只能解決2個值都為空。
不能解決order值為空但是title值為空時還是會出現(xiàn)語句錯誤的情況,這個時候我們可以在and 前面用1=1或者true來解決
如:

或這樣

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

