問(wèn)題描述
起因是在某次mybatis的select語(yǔ)句中使用了
update *** set
...
<if test="user.count"> count = #{user.count},</if>
...
來(lái)執(zhí)行更新user表各字段铐达,然后發(fā)現(xiàn)count = 0
的時(shí)候不會(huì)觸發(fā)count字段的更新,導(dǎo)致了bug出現(xiàn)簇搅。
解決方法和原因
猜測(cè)可能是源碼里面把0, '', null都當(dāng)作null來(lái)處理峦甩,類似弱類型的判斷,所以嘗試修改代碼:
<if test="user.count != null"> count = #{user.count},</if>
這次成功觸發(fā)了更新栏渺,果然是上述問(wèn)題呛梆。
查找相關(guān)資料后大概了解了原因,其實(shí)mybatis底層是用OGNL表達(dá)式來(lái)解析的磕诊,而這個(gè)表達(dá)式會(huì)把number類型的非0解析為true填物,把0解析為false,導(dǎo)致上述問(wèn)題觸發(fā)霎终,OGNL官網(wǎng)的描述如下:
Interpreting Objects as Booleans
Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:</br>
- If the object is a Boolean, its value is extracted and returned;</br>
- If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;</br>
- If the object is a Character, its boolean value is true if and only if its char value is non-zero;</br>
- Otherwise, its boolean value is true if and only if it is non-null.
所以修改為 !=null
即可解決這個(gè)類型轉(zhuǎn)換的問(wèn)題滞磺。