MyBatis OGNL 表达式陷阱:Integer类型字段使用“xxx!= ‘‘”时判断失效

问题原因

userTypeInteger 类型且值为 0 时,表达式 query.userType != '' 会判断失败。

根本原因

在 OGNL 表达式中,数字 0 会被当作 false 处理:

java 复制代码
<if test="query.userType != null and query.userType != ''">

userType = 0 时:

  • query.userType != nulltrue(0 不是 null)
  • query.userType != ''false(0 在 OGNL 中被当作 false)

因此整个表达式返回 false,导致 user_type = #{query.userType} 不会被添加到 SQL 中。

代码证据

`UserQuery.java`可以看到:

java 复制代码
@ApiModelProperty("用户类型(0:普通用户 1-管理员)")
private Integer userType;  // 注意:类型是 Integer

解决方案

方案一(推荐):只判断 null

xml 复制代码
<if test="query.userType != null">
    and user_type = #{query.userType}
</if>

方案二:使用 equals 方法

xml 复制代码
<if test="query.userType != null and query.userType != 0">
    and user_type = #{query.userType}
</if>

方案三:避免与空字符串比较数字类型

对于 IntegerLongDouble 等数值类型,不应该 与空字符串 '' 比较,因为这是类型不匹配的比较,容易触发 OGNL 的隐式类型转换问题。

最佳实践

字段类型 推荐判断条件
String query.field != null and query.field != ''
Integer/Long query.field != null
Date query.field != null
相关推荐
geovindu20 小时前
java: Memento Pattern
java·开发语言·后端·备忘录模式·行为模式
xcLeigh20 小时前
Unity基础:Start与Update方法——Unity脚本生命周期初探
java·unity·游戏引擎·教程
zephyr0520 小时前
链表实现O(n log n)时间复杂度的排序——归并排序详解
java·数据结构·算法
曾阿伦20 小时前
Trae CN Python环境调试debug指南
开发语言·python
Zane199420 小时前
JRE 去哪了?一次讲清楚 JDK、JRE、JVM 到底是什么关系?
java·后端
PPPPickup20 小时前
基础知识差缺补漏-面试版持续更新
java·开发语言
深入云栈20 小时前
Nacos 2.x 源码深度解析 (二):通信协议迭代 —— HTTP长轮询到gRPC演进
java
兔兔兔兔121 小时前
记录C++ 3
开发语言·c++
andongni20321 小时前
SpringBoot 入门实验报告
java·spring boot·后端
黄鸭部落格ShiYuYuanFang21 小时前
【分享】软考每日一练与解析-计组 8/12
java·开发语言