mybatis动态sql之map

参数为map的情况下,动态sql怎么写.

 

 

 上图是mapper里的方法定义.代码如下:

 void bulkMinus(@Param("map") Map<Long, Integer> map);

 

 

下面是其对应的xml里的sql

代码如下:

    <update id="bulkMinus">
        <foreach collection="map.entrySet()" item="value" index="key" separator=";">
            update tb_sku set stock=stock-#{value},sold=sold+#{value}
            <where>id=#{key}</where>
        </foreach>
    </update>

 

我这里的主要业务是根据商品id,批量减库存.即map里的key是商品id,value是卖出去的数量.下面是前端的传过来的请求参数.

 

 sql还有其它写法,这种应该是最简单的.

 

顺便记录下动态sql的易忘知识点.

    <!--
        foreach 标签(遍历)
            1. collection属性: 被遍历的容器类型
                list/array
            2. item : 被遍历出来的元素
            3. open: 遍历开始时的内容
            4. close: 遍历结束的内容
            5. separator : 每遍历一次就添加一次的分隔符(最后一次遍历不加)

        距离: list = {1,2,3}

            遍历: (1,2,3)
    -->
    <select id="findUsersByIds" resultType="user">
        select * from user where id in
        <foreach collection="list" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>

    </select>

    <select id="findUsersByIds2" resultType="user">
        select * from user where id in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>

    </select>

这里我主要是忘了open,close,separator三个东西的意思.上面代码中写成

open="(" close=")"

这样是因为sql是

select * from user where id in (x,y,z);

所以才写成括号的的,我也不知道还有什么其它的用法.

还有一个是separator,表示这次循环和下次循环之间的分隔符,我之前一直理解错了,特地记录下.

 

修改一下,上面的写法效率较低,需要执行多次sql,我又改进了一下,最后结果如下:

mapper接口里的方法定义

 

 void bulkMinus(@Param("map") Map<Long, Integer> map);

 

 xml里的sql如下:

 

 

 

<update id="bulkMinus">
UPDATE tb_sku SET stock=
<foreach collection="map.entrySet()" item="item" index="index" separator=" " open="case id" close="end,">
when #{index} then stock-#{item}
</foreach>
sold =
<foreach collection="map.entrySet()" item="item" index="index" separator=" " open="case id" close="end">
when #{index} then sold+#{item}
</foreach>
WHERE id IN
<foreach collection="map.entrySet()" item="item" index="index" separator="," open="(" close=")">
#{index}
</foreach>
</update>

请求参数同上,最后执行的sql为:

 

 

 

 这里也不用过多解释,反正就是一通拼接sql,达到最后的效果.navicat里的sql如下,代码和sql对照着看下就明白了.

 

 

 

  


UPDATE tb_sku SET
stock=
case id
when 2868393 then stock-2
when 2868435 then stock-5 end,
sold =
case id
when 2868393 then sold+2
when 2868435 then sold+5 end
WHERE id IN ( 2868393 , 2868435 )

 

posted @ 2020-11-26 23:17  重生之我是程序员  阅读(1277)  评论(0)    收藏  举报