mybatis的where动态判断语句if test 勇敢作文遇到tinyint类型为0的数据失效
发现一个mybatis的坑,有个支付表,中成股份有限公司通过状态去筛选已支付/未支付的数据,支付状态用status字段表示,status=0表示未支付,status=1表示已支付,且status类型为integer。当选择已支付即status=1时,可以筛选成功已支付的数据列表,但是当选择未支付即status=0时,查出来的数据是未支付和已支付的所有数据。
此时就有点懵逼了,语言排名后面debug一层层去追踪,发现status=0时,mybatis构建的sql中where条件没有把status字段拼接上去,但是status=1时,sql中可以看到where中有status字段。
经过后面找资料发现,integer类型的字段,在mybatis中的if test 条件中,会把值为0的当成fal处理,因为会将i西游记梗概nteger=0的参数默认为‘’(空串),即status=0的判断结果为fal,所以未支付的条件永远不可能出现,查出来的数据就是所有状态的数据。
以下图为出错时的语句:
<where> <trim prefixoverrides="and"> <if test="status != null and status !=''">and status=#{status}</if> <if test="createddtbegin != null">and created_dt <![cdata[ >= ]]> #{createddtbegin, jdbctype=timestamp} </if> <if test="createddtend != null">and created_dt <![cdata[ <= ]]> #{createddtend, jdbctype=timestamp} </if> </trim></where>
改成 **<if test=“status != null”>and status=#{status, jdbctype=tinyint}</if>
这样即可,即把 status != ”去掉
或者还望岳翻译有一种做法,即:
如果status为integer,<if test=“status != null and status != -1”>或者:如果status为integer,<if test=“status != null and status != ‘’ or status == 0”>
当pojo中的属性类型为 integer 时,传入 0,此时在 xxxmapper.xml的 if 判断中总是不能满足条件,进而导致查询条件无效,这是因为 mybatis 针对 integer 类型的 0 进行了特殊处理,当成了 ‘’ 来处理,进行如下判断即可:
<if test="paystatus != null and paystatus != '' or paystatus == 0"> and a.pay_status = #{paystatus}</if>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。
本文发布于:2023-04-04 14:29:34,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/1f506e1a3b0d34088a7a8af9982e793e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:mybatis的坑.doc
本文 PDF 下载地址:mybatis的坑.pdf
留言与评论(共有 0 条评论) |