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
相关推荐
二哈赛车手7 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
为何创造硅基生物7 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好7 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
栗子~~7 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
星寂樱易李7 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
YDS8298 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
仰泳之鹅8 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆8 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
未若君雅裁9 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
cen__y9 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git