Mybatis的xml中使用if/else標簽的具體使用
使用if標簽進行查詢
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的話運行會報錯,就算第一個if等于null 那么查詢語句變成 where and title='哈哈哈'
這樣運行的話也會出現(xiàn)錯誤。
where標簽出場
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 元素也會將它們去除。這個只能解決2個值都為空。
不能解決order值為空但是title值為空時還是會出現(xiàn)語句錯誤的情況,這個時候我們可以在and 前面用1=1或者true來解決
如:
或這樣
if/else 使用 choose,when,otherwise 代替
由于Mybatis中沒有else標簽但是可以通過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>
翻譯一下上面的語句:
當platformtype 值不為空并且把platformtype 值進行去除空字符串,并且值等于1時
就會把表orders_A進行拼接,如果條件都不符合的話就會走otherwise標簽默認拼接orders_A表進行查詢
choose,when,otherwise標簽有點像Java中的switch 當where的test值滿足時會拼接里面的表,otherwise表示其他when標簽都不滿足時執(zhí)行拼接
到此這篇關于Mybatis的xml中使用if/else標簽的具體使用的文章就介紹到這了,更多相關Mybatis xml=使用if/else標簽內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java通過綁定實現(xiàn)快速將數(shù)據(jù)導出至Excel
把數(shù)據(jù)導出至?Excel?是很常見的需求,而數(shù)據(jù)的持久化,往往又放在數(shù)據(jù)庫中,因此把數(shù)據(jù)庫中的數(shù)據(jù)導出到?Excel中,成了非常普遍的一個需求,下面我們就來看看Java如何通過綁定實現(xiàn)快速將數(shù)據(jù)導出至Excel吧2023-10-10舉例講解Java的Spring框架中AOP程序設計方式的使用
這篇文章主要介紹了Java的Spring框架中AOP程序設計方式的使用講解,文中舉的AOP下拋出異常的例子非常實用,需要的朋友可以參考下2016-04-04SpringBoot+Redis實現(xiàn)后端接口防重復提交校驗的示例
本文將結合實例代碼,介紹SpringBoot+Redis實現(xiàn)后端接口防重復提交校驗的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06springboot中使用ElasticSearch的詳細教程
這篇文章主要介紹了ElasticSearch在springboot中使用的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05