问题描述
起因是在某次mybatis的select语句中使用了
update *** set
...
<if test="user.count"> count = #{user.count},</if>
...
来执行更新user表各字段,然后发现count = 0
的时候不会触发count字段的更新,导致了bug出现。
解决方法和原因
猜测可能是源码里面把0, '', null都当作null来处理,类似弱类型的判断,所以尝试修改代码:
<if test="user.count != null"> count = #{user.count},</if>
这次成功触发了更新,果然是上述问题。
查找相关资料后大概了解了原因,其实mybatis底层是用OGNL表达式来解析的,而这个表达式会把number类型的非0解析为true,把0解析为false,导致上述问题触发,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
即可解决这个类型转换的问题。