MyBatis+SpringMVC+SpringBoot

mybatis动态sql中test判断Boolean

2018-11-30  本文已影响4人  帮我的鸵鸟盖个章
mybatis中动态sql使用if test判断String,pojo一般写法如下(sql片段):

String

<if test="countryArea != null and countryArea != ''">
    AND country_area=#{countryArea}
</if>

pojo

<if test="map.keyWord != null and map.keyWord != ''">
    AND s.subject LIKE concat('%',#{map.keyWord},'%')
</if>
但是如果是Boolean类型,如果写成如下方式,会出现false无效的bug,一直执行的都是true
<update id="updateHaveNewComment">
        <choose>
            <when test="flag=true">
                UPDATE epc_subject_center s
                SET s.have_new_comment=1
                WHERE s.id=#{id}
            </when>
            <otherwise>
                UPDATE epc_subject_center s
                SET s.have_new_comment=0
                WHERE s.id=#{id}
            </otherwise>
        </choose>
    </update>
网上有一些资料说只用判断是否为null就可以了,个人检验是错误的。下面的也是错误的
<update id="updateHaveNewComment">
        <choose>
            <when test="flag !=null">
                UPDATE epc_subject_center s
                SET s.have_new_comment=1
                WHERE s.id=#{id}
            </when>
            <otherwise>
                UPDATE epc_subject_center s
                SET s.have_new_comment=0
                WHERE s.id=#{id}
            </otherwise>
        </choose>
    </update>

正确的写法应该是

<update id="updateHaveNewComment">
        <choose>
            <when test="flag">
                UPDATE epc_subject_center s
                SET s.have_new_comment=1
                WHERE s.id=#{id}
            </when>
            <otherwise>
                UPDATE epc_subject_center s
                SET s.have_new_comment=0
                WHERE s.id=#{id}
            </otherwise>
        </choose>
    </update>

或者

<update id="updateHaveNewComment">
        <choose>
            <when test="flag==true">
                UPDATE epc_subject_center s
                SET s.have_new_comment=1
                WHERE s.id=#{id}
            </when>
            <otherwise>
                UPDATE epc_subject_center s
                SET s.have_new_comment=0
                WHERE s.id=#{id}
            </otherwise>
        </choose>
    </update>
上一篇 下一篇

猜你喜欢

热点阅读