文章目录

一、背景

mybatis语法掌握不熟,在写foreach操作时,造成in ()错误,这种情况不符合SQL的语法,导致程序报错。

如果简单只做非空判断,这样也有可能会有问题:本来in一个空列表,应该是没有数据才对,却变成了获取全部数据!


二、错误sql示例

<select id="getActiveCount" resultType="int" parameterType="com.missfresh.active.dto.ActiveSearchDTO">
        select count(1) from (
        SELECT
        distinct  a.*
        FROM
        active AS a
        <if test="sku!='' and sku!=null">
            LEFT JOIN active_promotion AS ap ON ap.active_id = a.id
            LEFT JOIN promotion_product AS pp ON pp.promotion_id = ap.promotion_id
        </if>
        <if test="areaIds!='' and areaIds!=null">
            LEFT JOIN active_area AS aa ON aa.active_id = a.id and aa.status = 1 and aa.area_type = 0
        </if>
        WHERE a.status <![CDATA[!= ]]> 0
        <if test="id!=0 and id!=null">
            AND a.id = #{id}
        </if>
        <if test="name!='' and name!=null">
            AND a.name LIKE CONCAT('%',#{name},'%')
        </if>
        <if test="sku!='' and sku!=null">
            AND pp.sku = #{sku}
        </if>
        <!--判断方式错了,应该先用null再用size>0判断;如果areaIds为空,查询结果也应为空,而不是其他查询结果。所以sql有问题-->
        <if test="areaIds!='' and areaIds!=null">
            and aa.area_id IN
            <foreach item="item" index="index" collection="areaIds" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        order by a.create_time desc ) as b

    </select>

三、改正后的sql为:

<select id="getActiveCount" resultType="int" parameterType="com.missfresh.active.dto.ActiveSearchDTO">
        select count(1) from (
        SELECT
        distinct  a.*
        FROM
        active AS a
        <if test="sku!='' and sku!=null">
            LEFT JOIN active_promotion AS ap ON ap.active_id = a.id
            LEFT JOIN promotion_product AS pp ON pp.promotion_id = ap.promotion_id
        </if>
        <if test="areaIds!='' and areaIds!=null">
            LEFT JOIN active_area AS aa ON aa.active_id = a.id and aa.status = 1 and aa.area_type = 0
        </if>
        WHERE a.status <![CDATA[!= ]]> 0
        <if test="id!=0 and id!=null">
            AND a.id = #{id}
        </if>
        <if test="name!='' and name!=null">
            AND a.name LIKE CONCAT('%',#{name},'%')
        </if>
        <if test="sku!='' and sku!=null">
            AND pp.sku = #{sku}
        </if>
        <if test="areaIds!=null and areaIds.size > 0">
            and aa.area_id IN
            <foreach item="item" index="index" collection="areaIds" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <!--加入这个非真条件-->
        <if test="areaIds!=null or areaIds.size ==  0">
        and 1=0
        </if>
        order by a.create_time desc ) as b
    </select>

四、参考链接:

https://www.cnblogs.com/xujanus/p/7611401.html

02-12 00:42