Mybatis中<if>和<choose>的區(qū)別及“=”判斷方式
<if>和<choose>的區(qū)別及“=”判斷
在項目中xml文件經(jīng)常會遇到在判斷等于某個值時加什么條件不等于某個值的時候加什么條件
比如下面這個例子:
<if ?test=" name != null">
?? ?AND T.NAME = #{NAME,jdbcType=VARCHAR}
</if>
<if ?test=" name ?== null">
?? ?ORDER BY NAME,ID
</if>正確很好的寫法需要引入<choose>標簽
?<choose>
? ? ? ?<when test=" name != null">
? ? ? ? ? AND T.NAME = #{NAME,jdbcType=VARCHAR}
? ? ? </when>
? ? ?<otherwise>
? ? ? ? ORDER BY T.PRODUCT_TYPE_CODE, T.SORT DESC, T.CREATE_TIME
? ? ?</otherwise>
</choose>第一種錯誤寫法導致的結(jié)果就是不會去做任何判斷即使name不為空。
為什么只能用<choose>標簽,源碼還沒有研究,或者我這個例子本身就有問題現(xiàn)在記錄下來,在后續(xù)的更新中我會再次總結(jié)一下這個問題。
<!--錯誤的寫法-->
<if test="newsImage != null and newsImage == 'y'"> ? ? ? <![CDATA[ and len(newsImage) > 0 ]]> ? </if> ? <!-- 正確的,穩(wěn)定,推薦使用 --> ? <if test="newsImage != null and newsImage == 'y'.toString()"> ? ? ? <![CDATA[ and len(newsImage) > 0 ]]> ? </if> ?
判斷 newsImage == 'y' 時,有人認為成功,但實際上是不成功的,需要改為 newsImage == 'y'.toString()方可成功,
原因具體沒有細入研究,根據(jù)實際使用推測應該是 “等于” 在java中是個比較復雜問題,涉及的“等于”有可能是變量地址相等,或者是變量值內(nèi)容相等,在XML文件中簡單的 == 在經(jīng)過MyBatis處理后無法判斷是哪種類型的“相等”,所以加.toString()做強制轉(zhuǎn)換操作,MyBatis就知道是值內(nèi)容的比較,當然就成功了;
注意這個常量不限于數(shù)字,對于字母,如 'y' 同樣需要加上 .toString()方可成功。
Mybatis選擇choose和條件if用法
choose用法
? ? ? ? <choose> ?? ??? ??? ?<when test="showType == 1"> ?? ??? ??? ??? ?IFNULL(k.fname,'未知') as pro_name, ?? ??? ??? ?</when> ?? ??? ??? ?<when test="showType == 2"> ?? ??? ??? ??? ?IFNULL(e.fname,'未知') as business_name, ?? ??? ??? ?</when> ?? ??? ??? ?<when test="showType == 3"> ?? ??? ??? ??? ?IFNULL(f.fname,'未知') as area_name, ?? ??? ??? ?</when> ?? ??? ??? ?<when test="showType == 4"> ?? ??? ??? ??? ?IFNULL(h.fname,'未知') as sale_name, ?? ??? ??? ?</when> ?? ??? ??? ?<otherwise> ?? ??? ??? ??? ?IFNULL(j.F_PJQD_XMDJ,'未知') as project_type, ?? ??? ??? ?</otherwise> ?? ??? ?</choose>
if用法
? ? ? ? <if test="businessName != null and businessName != ''">
?? ??? ??? ?and e.fname = #{businessName}
?? ??? ?</if>
?? ??? ?<if test="areaName != null and areaName != ''">
?? ??? ??? ?and f.fname = #{areaName}
?? ??? ?</if>以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring AI Alibaba接入大模型時的依賴問題小結(jié)
文章介紹了如何在pom.xml文件中配置SpringAI Alibaba依賴,并提供了一個示例pom.xml文件,同時,建議將Maven倉庫鏡像設置為阿里云以提高下載速度,具體配置方法跟隨小編一起學習下吧2025-02-02
如何在springMVC的controller中獲取request
這篇文章主要介紹了如何在springMVC的controller中獲取request,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
java 裝飾模式(Decorator Pattern)詳解及實例代碼
裝飾器模式(Decorator Pattern)允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結(jié)構(gòu)。這種類型的設計模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類的一個包裝2016-10-10

