正确代码参考: 我传递的keyword 还有type都是String类型的。status是Integer类型的,传的值是0。
<select id="selectData" resultType="com.susu.demo.Test">
SELECT
t.id,
t.nam
FROM
test t
WHERE 1=1
<if test="keyword != null and keyword != ''">
AND t.name like concat('%',#{keyword},'%')
</if>
<if test="type != null and type != ''">
AND t.type = #{type}
</if>
<if test="status != null">
AND t.status = #{status}
</if>
ORDER BY
<if test="order =='asc' ">
create_time ASC
</if>
<if test="order =='desc' ">
create_time DESC
</if>
</select>
那么,什么情况下出问题了呢?如果用下面的代码来判断Integer类型,那么sql中就不会含有status的字段,也就是漏掉了这个判断。
<if test="status != null and status != ''"> AND t.status = #{status} </if>
根据上面错误的代码逻辑,推测 mybatis是不是把这个 status = 0 在判断条件 status != ''时当作是 false了,所以这块的代码逻辑不起作用。而且,通过去掉 and status != ''的时候,这个sql又正常了,会包含这个statu=0的筛选条件。
mybatis的if标签,是通过OGNL表达式处理的。接下来,我们查看一下OGNL的文档:
如果对象是Number类型,当传值为0时会被解析成false,否则为true,浮点型0.00也是如此。所以这里直接解析成false。只有String类型才需要判断是否 != ' ',其他类型完全就不需要判断这个!=''了。