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

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

 更新時(shí)間:2022年06月06日 14:09:13   作者:Simple_Demo  
這篇文章主要介紹了Mybatis中<if>和<choose>的區(qū)別及“=”判斷方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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

在項(xiàng)目中xml文件經(jīng)常會(huì)遇到在判斷等于某個(gè)值時(shí)加什么條件不等于某個(gè)值的時(shí)候加什么條件

比如下面這個(gè)例子:

<if ?test=" name != null">
?? ?AND T.NAME = #{NAME,jdbcType=VARCHAR}
</if>
<if ?test=" name ?== null">
?? ?ORDER BY NAME,ID
</if>

正確很好的寫(xiě)法需要引入<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>

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

為什么只能用<choose>標(biāo)簽,源碼還沒(méi)有研究,或者我這個(gè)例子本身就有問(wèn)題現(xiàn)在記錄下來(lái),在后續(xù)的更新中我會(huì)再次總結(jié)一下這個(gè)問(wèn)題。

<!--錯(cuò)誤的寫(xiě)法-->

<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' 時(shí),有人認(rèn)為成功,但實(shí)際上是不成功的,需要改為  newsImage == 'y'.toString()方可成功,

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

注意這個(gè)常量不限于數(shù)字,對(duì)于字母,如 '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>

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。 

相關(guān)文章

最新評(píng)論