在使用mysql动态查询时遇到的一个问题,查询语句如下:
WHERE1=1
<!-- 使用动态SQL进行条件判断 -->
<if test="status != null and status != ''">AND u.STATUS = #{status}
</if>
其中 STATUS是一个Integer型枚举值(0,1),问题就是当从前端传进来的参数status为1时能被mybatis解析,而当status为0时这个判断条件直接被忽略了。
原因是在MyBatis中,会将0
视为false
,而不是作为真正的值传递。这是因为在XML配置文件中,<if>
标签的test
属性实际上是一个Ognl表达式,而Ognl表达式中的0
会被当作false
处理,即 ‘’ == 0 == false.
解决办法:
第一种:
<if test="status != null and status .toString() != ''"> AND u.STATUS = #{status} </if>
第二种:
<if test="status != null and status .toString() != ''"> AND u.STATUS = #{status} </if>
第三种:
<if test="status != null or status == 0> AND u.STATUS = #{status} </if>
这样无论status
是null
还是0
,都能被正确传入作为参数。