MyBatis 踩坑:数字 0 传入后 if 判断失效,更新字段不生效问题解析

📅 2026/6/26 1:17:43
MyBatis 踩坑:数字 0 传入后 if 判断失效,更新字段不生效问题解析
一、问题现象业务场景为物料库存更新接口使用 FastJSON 的 JSONObject 接收入参MyBatis 动态 SQL 通过if标签判断字段是否参与更新入参newQuantity传入数值0Integer 类型XML 中判断条件if testnewQuantity ! null and newQuantity ! 最终打印的执行 SQL 完全没有拼接invt #{newQuantity}这一段库存字段未更新当newQuantity传入大于 0 的数字如 2、5时SQL 正常拼接更新逻辑生效。二、根因分析1. OGNL 表达式底层判定规则MyBatis 的if test使用 OGNL 表达式做条件判断当数字 0与**空字符串**做不等对比时0 ! 的运算结果为false。完整条件newQuantity ! null and newQuantity ! 逻辑拆解newQuantity0newQuantity ! null→ truenewQuantity ! → falsetrue false整体条件不成立if分支直接跳过对应字段不会拼入 SQL。2. 混用字符串、数字判断是核心误区! 是专门用于字符串类型的判空逻辑用来过滤前端传过来的空字符串而库存、金额、单价、税额这类字段存储类型为 Integer/BigDecimal入参只会是null或数字永远不会出现空字符串强行叠加! 判断会拦截数值 0。3. 同类受影响字段代码中所有金额、数值字段都存在相同隐患amount_inclusive_tax、unit_pr、amount_tax、amount_no_tax当传入 0 时都会出现更新失效。三、两种解决方案方案 1数值字段最优方案推荐数字类型字段仅判断null直接删除! 条件不做空字符串校验!-- 库存数量Integer --iftestnewQuantity ! nullinvt #{newQuantity},/if!-- 含税金额BigDecimal --iftestamount_inclusive_tax ! nullamount_inclusive_tax #{amount_inclusive_tax},/if优势逻辑简洁、无多余运算完美兼容 0、正数、负数等所有数字场景。方案 2兼容字符串 数字混合入参场景若字段存在同时接收字符串、数字的特殊场景补充数字 0 的判断逻辑iftestnewQuantity ! null and (newQuantity ! or newQuantity 0)invt #{newQuantity},/if劣势多一层逻辑判断纯数值业务不推荐使用。四、规范区分什么时候用! 什么时候只用! null字符串字段名称、编码、备注、地址需要双重判断过滤null和前端空字符串iftestartiName ! null and artiName ! arti_name #{artiName},/if数值字段Integer、Long、BigDecimal、Double仅判断非 null禁止加! iftestchangeQuantity ! nullinvt #{changeQuantity},/if五、修正后完整 XML 示例updateidupdateInvtQuantityparameterTypecom.alibaba.fastjson.JSONObjectUPDATE LCP_ARTI_MATN_HQZX SETiftestnewQuantity ! nullinvt #{newQuantity},/ififtestamount_inclusive_tax ! nullamount_inclusive_tax #{amount_inclusive_tax},/ififtestunit_pr ! nullunit_pr #{unit_pr},/ififtestamount_tax ! nullamount_tax #{amount_tax},/ififtestamount_no_tax ! nullamount_no_tax #{amount_no_tax},/ifsysupdatedate SYSDATE, sysupdateoruuid #{syscreatoruuid}, sysupdateoruuidname #{syscreatoruuidname} WHERE matn_id #{matnId} AND sysisdelete 0/update六、总结避坑要点数字字段不要混用空字符串判断! 会拦截数值 0严格区分字段类型字符串双重判空、数值仅判 null开发完成后务必覆盖入参为 0的场景做单元测试避免库存清零、金额置零等业务逻辑失效打印 MyBatis 执行 SQL 日志辅助排查动态分支是否正常拼接。