1. 程式人生 > >mybatis中if判斷把整數0識別為false(深坑)

mybatis中if判斷把整數0識別為false(深坑)

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的有一條資料,如下圖:


4 測試結果根據settleStatus傳入0,卻返回3條記錄,如下圖:


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>