MyBatis中0和''的坑

124 阅读1分钟

起因

在实际业务中, 我们经常会遇到判断某个数据库字段等于0的情况

例如任务状态status = 0, 我们把它作为查询任务的条件传入MyBatis

在下面这种情况下, 这个查询条件就会失效:

<where>
    <if test="parameters.status != null and parameters.status != ''">
        t.status = #{parameters.status}
    </if>
</where>

原因

在Mybatis中, 默认0==''

解决方案

只需要增加一个判断条件即可

<where>
    <if test="parameters.status != null and parameters.status != '' or parameters.status == 0">
        t.status = #{parameters.status}
    </if>
</where>