欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mybatis中<if>和<choose>的區(qū)別及“=”判斷方式

 更新時間:2022年06月06日 14:09:13   作者:Simple_Demo  
這篇文章主要介紹了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>標(biāo)簽

?<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>

第一種錯誤寫法導(dǎo)致的結(jié)果就是不會去做任何判斷即使name不為空。

為什么只能用<choose>標(biāo)簽,源碼還沒有研究,或者我這個例子本身就有問題現(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' 時,有人認(rèn)為成功,但實際上是不成功的,需要改為  newsImage == 'y'.toString()方可成功,

原因具體沒有細(xì)入研究,根據(jù)實際使用推測應(yīng)該是 “等于” 在java中是個比較復(fù)雜問題,涉及的“等于”有可能是變量地址相等,或者是變量值內(nèi)容相等,在XML文件中簡單的 == 在經(jīng)過MyBatis處理后無法判斷是哪種類型的“相等”,所以加.toString()做強制轉(zhuǎn)換操作,MyBatis就知道是值內(nèi)容的比較,當(dāng)然就成功了;

注意這個常量不限于數(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)文章

最新評論