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 > #{ipBlackDto.timeStart} " + "</if>"
原文鏈接:https://blog.csdn.net/u012204058/article/details/102518777