问题:
中奖状态 win_status(0 未中奖 1 已中奖) 字段是tinyint类型,winStatus是Integer。想通过条件查询中奖的数据和没有中奖的数据,但是传入winStatus == 0 时,预期是查询所有未中奖的数据,但是if test标签并没有生效,查询的依然是全部数据。
原代码(错误代码)
<where>
<if test="winStatus != '' and winStatus != null">
AND atjl.win_status = #{winStatus}
</if>
</where>
原因解析
integer winStatus = 0 类型的变量,在mybatis中的if test 条件中,会将Integer = 0
的参数默认为 ''
(空串),即Integer winStatus = ' '
,所以 <if test=" winStatus != ' ' and winStatus != null">
中的 winStatus != ' '
被判定为false
,if test不被执行,所以查询条件没有拼接,最终查询出来的依然是全部的数据。
解决方法
方法一:
去掉 winStatus != ' '
winStatus是整类,前端传递空字符串的时候一般会判定不传此参数,最后后端接收的是null,可以选择直接去掉。
修改后的代码
<where>
<if test="winStatus != null">
AND atjl.win_status = #{winStatus}
</if>
</where>
方法二
保险一点 的方法
<where>
<if test="winStatus != null and winStatus != '' or winStatus == 0">
AND atjl.win_status = #{winStatus}
</if>
</where>