mybatis中 if test判断容易踩的坑

问题描述

起因是在某次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即可解决这个类型转换的问题。

参考文章:

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容