Mybatis if test 条件参数为0的一个坑

Posted 不允许摆烂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis if test 条件参数为0的一个坑相关的知识,希望对你有一定的参考价值。

问题描述

今天发现mybatis if test 条件参数为0的一个坑,在此记录一下

主要内容如下

原代码,我是要用用户id作为参数进行拼接查询的

  <if test="sign.userId!=null and sign.userId!=''">
         and ds.user_id=#sign.userId
  </if>

 看起来好像没什么问题,就是userId不为空的时候,进行拼接查询,然后我就调用接口

 查出来的数据是不对的,我看了下日志执行的sql如下

select ds.id, ds.company_name, ds.title, ds.user_id, ds.confirm_time , ds.remark, ds.sign_type, dsi.signator_status, dsi.company_name as otherCompanyName from dmyz_sign ds left join dmyz_signator dsi on ds.id = dsi.sign_id where ds.is_deleted = 0 

很明显没有把参数加进来,也就是说在if标签判断里面 0是没用通过的

通过查询资料发现

mybatis查询时。遇到这种如果传进来的的参数值为0 ,直接跳出if不执行

问题在于参数类型
’’ != userId 只能作用于string,int 、double、float等类型的参数默认值为0 ,将直接跳出if,
删掉后面的空字符串判断即可

解决方案

改为这种方式

 <if test="null !=sign.userId ">
                and ds.user_id=#sign.userId
</if>

再次运行,完美解决

以上是关于Mybatis if test 条件参数为0的一个坑的主要内容,如果未能解决你的问题,请参考以下文章

mybatis条件判断

mybatis的 if test 条件判断字符串单双引号解析问题

mybatis if test 采坑记

mybatis怎么设置当不满足所有if test的条件则返回空?

Mybatis if test 判断 list不为 null 并且判断集合大小不为0

mybatis----Integer = 0 刷选不出来条件原因以及sql改法