mybatis条件构造bug

作者 : admin 本文共975个字,预计阅读时间需要3分钟 发布时间: 2024-06-6 共1人阅读

一、需求背景

(本文源自微博客,且已获得授权)
     根据传递的参数,使用mybatis-plus动态构造查询语句。参数对象如下:

    private Integer id;
    private String ip;
    /**
     * 状态:0封锁;1:已解封
     */
    private Integer status;
    /**
     * 开始时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date startTime;

    /**
     * 结束时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date endTime;

部分构造条件如下:


<if test="req.status != null and req.status != '' and  req.status == 1">
    <choose>
        <when test="req.endTime == null">
            AND (status = 1 OR end_time <span class="token entity named-entity" title="< NOW())
        </when>
        <otherwise>
            AND status = 1
        </otherwise>
    </choose>
</if>

<if test="req.status != null and req.status != '' and req.status != 1">
    AND status = #{req.status}
</if>

二、问题描述

      当我传递的参数如:

{
  "current": 1,
  "size": 5,
  "status": 1
}

时,能够按照我的逻辑正确构造查询条件,即条件可以满足,可是,当传递的参数如下:

{
  "current": 1,
  "size": 5,
  "status": 0
}

时,无法按照我的逻辑来处理,即条件 不满足。经过多次断点排查,最后发现问题出现在实体类型的private Integer status;上面,因为 status是 Integer类型的,所以根本就不能与string中的‘’做比较,(诡异的是能满足条件且不会有任何异常提示这应该算是mybatis的一个bug吧)。

三、解决方案

     既然知道问题所在,就可以按图索骥对症下药了: 删掉 and req.status != '' 这个多余的条件判断即可。

本站无任何商业行为
个人在线分享 » mybatis条件构造bug
E-->