問題描述
起因是在某次mybatis的select語句中使用了
update *** set
...
<if test="user.count"> count = #{user.count},</if>
...
來執(zhí)行更新user表各字段,然后發(fā)現count = 0的時候不會觸發(fā)count字段的更新,導致了bug出現。
解決方法和原因
猜測可能是源碼里面把0, '', null都當作null來處理,類似弱類型的判斷,所以嘗試修改代碼:
<if test="user.count != null"> count = #{user.count},</if>
這次成功觸發(fā)了更新,果然是上述問題。
查找相關資料后大概了解了原因,其實mybatis底層是用OGNL表達式來解析的,而這個表達式會把number類型的非0解析為true,把0解析為false,導致上述問題觸發(fā),OGNL官網的描述如下:
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即可解決這個類型轉換的問題。