Mybatis批量新增和修改

接口:

//批量新增
int batchInsertGoods(List<Goods> list);

//批量修改
int batchUpdateCarsByIds(List<Map<String, Object>> list);

//根据ids批量获取Goods列表
List<Map<String, Object>> getGoodsList(List<String> ids);

//同一对象根据多个字段批量删除
void batchDelete(List<Goods> goods);

Mybatis:

<!-- 批量新增-->
<insert id="batchInsertGoods" parameterType="java.util.List">
    INSERT INTO t_goods(i_id, goods_name)
    VALUES
    <foreach collection="list" item="item" separator=",">
        (#{item.id,jdbcType=VARCHAR},#{item.goodsName,jdbcType=VARCHAR})
    </foreach>
</insert>

<!-- 批量修改方式-->
<update id="batchupdateCarsByIds" parameterType="java.util.List">
      update t_car
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="car_number = case" suffix="else car_number end,">
                <foreach collection="list" item="car" index="index">
                    <if test="car.carNumber != null and car.carNumber != ''">
                        when i_id = #{car.id} then #{car.carNumber}
                    </if>
                </foreach>
            </trim>
            <trim prefix="car_name = case" suffix="else car_name end,">
                <foreach collection="list" item="car" index="index">
                    <if test="car.carName != null">
                        when i_id = #{car.id} then #{car.carName}
                    </if>
                </foreach>
            </trim>
        </trim>
        where i_id in
        <foreach collection="list" item="car" index="index" separator="," open="(" close=")">
            #{car.id}
        </foreach>
</update>


<!-- 根据ids批量获取Goods列表-->
<select id="getGoodsList" parameterType="java.util.List" resultType="java.util.Map" >
    SELECT i_id, goods_name FROM t_goods WHERE i_id in
       <foreach collection="list" item="item" index="index" open="(" separator="," close=")">
           #{item}
       </foreach>
</select>

<!-- 根据多个字段批量删除-->
<delete id="batchDelete" parameterType="java.util.List">
        DELETE
        FROM t_goods
        WHERE (good_code, good_name) in
        <foreach collection="list" open="(" close=")" item="item" separator=",">
            (#{item.goodCode}, #{item.goodName})
        </foreach>
</delete>

mysql输出:

-- 批量新增
INSERT INTO goods(id, goods_name)
VALUES
(?, ?),
(?, ?);

-- 批量修改,不为空则修改,为空则不修改(goods.goods_name,goods.iorder代表不修改)
UPDATE goods set goods_name = case when id = ? then ? when id = ? then goods.goods_name end, 
iorder = case when id = ? then goods.iorder when id = ? then ? end 
WHERE id in ( ? , ? );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值