mybatis中if判断把整数0识别为false(深坑)

时间:2024-03-24 15:51:52

1先看mybatis配置文件

<select id="listByParam"   resultMap="orderSettlePartnerResultMap" parameterType="com.jd.ept.settlement.domain.settle.OrderSettlePartner">

    SELECT
    <include refid="all_table_column"/>
    FROM
    order_settle_partner
    where 1=1
    <if test="settleStatus != null and settleStatus !=''">
        AND settle_status = #{settleStatus}
    </if>

</select>

2再看Java测试方法

@Test
public void testByParam() {
    OrderSettlePartner orderSettlePartner=new OrderSettlePartner();
    orderSettlePartner.setSettleStatus(0);
    orderSettlePartner.setPartnerId(1);
    List<OrderSettlePartner>  orderSettlePartnerList = orderSettlePartnerMapper.listByParam(orderSettlePartner);
    System.out.println(orderSettlePartnerList.size());
}

3 settleStatus是Integer类型,order_settle_partner表里settle_status为0的有2条数据,为1的有一条数据,如下图:

mybatis中if判断把整数0识别为false(深坑)

4 测试结果根据settleStatus传入0,却返回3条记录,如下图:

mybatis中if判断把整数0识别为false(深坑)

5错误原因:

  1. <if test="settleStatus != null and settleStatus != ''">settleStatus为integer类型的,settleStatus=0的判断结果为false,mybatis把settleStatus作为了string来进行判断。

6解决办法:去掉settleStatus !=''的判断,改成下面的判断

<if test="settleStatus != null">
    AND settle_status = #{settleStatus}
</if>