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

问题原因

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

根本原因

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

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

当 userType = 0 时:

  • query.userType != null → true(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>

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

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

最佳实践

字段类型 推荐判断条件
String query.field != null and query.field != ''
Integer/Long query.field != null
Date query.field != null
相关推荐
Joy T5 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
m0_587383008 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
·云扬·8 小时前
Prompt 工程与安全:从 System 设计到注入防御
java·人工智能·安全·ai·prompt
专注仿真8 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
Best-Wishes8 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停9 小时前
自动化测试(java)
java·开发语言·selenium·自动化
鬼手点金11 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
爱上网的小舟11 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php
paopaokaka_luck12 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts
阿里嘎多学长12 小时前
2026-10-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管