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
相关推荐
2401_891482172 分钟前
C++中的代理模式实战
开发语言·c++·算法
独断万古他化5 分钟前
【抽奖系统开发实战】Spring Boot 抽奖模块全解析:MQ 异步处理、缓存信息、状态扭转与异常回滚
java·spring boot·redis·后端·缓存·rabbitmq·mvc
weisian1519 分钟前
Java并发编程--12-读写锁与StampedLock:高并发读场景下的性能优化利器
java·开发语言·性能优化·读写锁·stampedlock
2401_8386833710 分钟前
C++中的代理模式高级应用
开发语言·c++·算法
暮冬-  Gentle°5 小时前
C++中的命令模式实战
开发语言·c++·算法
Volunteer Technology7 小时前
架构面试题(一)
开发语言·架构·php
清水白石0087 小时前
Python 对象序列化深度解析:pickle、JSON 与自定义协议的取舍之道
开发语言·python·json
2401_876907527 小时前
Python机器学习实践指南
开发语言·python·机器学习
努力中的编程者8 小时前
栈和队列(C语言底层实现环形队列)
c语言·开发语言
xdl25998 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis