mybatis的if test=0的小坑


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的当成false处理,因为会将integer=0的参数默认为‘’(空串),即status=0的判断结果为false,所以未支付的条件永远不可能出现,查出来的数据就是所有状态的数据。

以下图为出错时的语句:

<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 != ''去掉

 

 

 

对字符串的判断

+"<if test='ipBlackDto.timeStart!=null and ipBlackDto.timeStart != \"\"'> "
            + " and i.create_time &gt; #{ipBlackDto.timeStart} "
            + "</if>"

 原文链接:https://blog.csdn.net/u012204058/article/details/102518777


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM