mybatis中 if test判断容易踩的坑

问题描述

起因是在某次mybatis的select语句中使用了

update *** set
...
 count = #{user.count},
...

来执行更新user表各字段,然后发现count = 0的时候不会触发count字段的更新,导致了bug出现。

解决方法和原因

猜测可能是源码里面把0, '', null都当作null来处理,类似弱类型的判断,所以尝试修改代码:

 count = #{user.count},

这次成功触发了更新,果然是上述问题。

查找相关资料后大概了解了原因,其实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:

  • If the object is a Boolean, its value is extracted and returned;
  • 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;
  • If the object is a Character, its boolean value is true if and only if its char value is non-zero;
  • Otherwise, its boolean value is true if and only if it is non-null.

所以修改为 !=null即可解决这个类型转换的问题。

参考文章:

https://www.cnblogs.com/grasp/p/11268049.html

你可能感兴趣的:(mybatis中 if test判断容易踩的坑)