MyBatis批量操作整合

MyBatis批量操作包括:批量新增、批量更新以及批量删除。

1.批量新增:一条insert语句插入多条记录

INSERT INTO t_mobile_ownership (id, province, city, ownership, segment, area_no, card_type, postcode, operator)
VALUES (1,...),(2,...)

xml代码示例:

<!-- 批量新增手机号归属地信息 -->
    <insert id="insertBatch" parameterType="java.util.List">
        INSERT INTO
        	t_mobile_ownership
        (id, province, city, ownership, segment, area_no, card_type, postcode, operator)
        VALUES
        <foreach collection="mobileList" item="item" separator=",">
            (#{item.id},#{item.province},#{item.city},#{item.ownership},#{item.segment},
            #{item.areaNo},#{item.cardType},#{item.postcode},#{item.operator}
            )
        </foreach>
    </insert>


2.批量更新:一条update语句更新多条记录

Mysql并未提供方法实现批量更新,此处可以使用case when语句来实现批量更新操作。

xml代码示例:

<!-- 批量更新手机号归属地信息 -->
    <update id="updateBatch" parameterType="java.util.List">
    	UPDATE t_mobile_ownership
        <trim prefix="set" suffixOverrides=",">
        	<!-- 所属省 -->
            <trim prefix="province =case" suffix="end,">
                <foreach collection="mobileList" item="item">
                    <if test="item.province != null">
                        when id = #{item.id} then #{item.province}
                    </if>
                </foreach>
            </trim>
            <!-- 区号 -->
            <trim prefix="area_no =case" suffix="end,">
                <foreach collection="mobileList" item="item">
                    <if test="item.areaNo != null">
                        when id = #{item.id} then #{item.areaNo}
                    </if>
                </foreach>
            </trim>
        </trim>
        WHERE
        	id IN
        <foreach collection="mobileList" item="item" separator="," open="(" close=")">
           #{item.id}
        </foreach>
    </update>

以上代码实际执行sql如下:

UPDATE
    t_mobile_ownership
SET province = CASE id
    WHEN 1 THEN '江苏'
    WHEN 2 THEN '浙江'
END,
area_no = CASE id 
    WHEN 1 THEN '025'
    WHEN 2 THEN '0570'
END
WHERE
    id IN (1,2)


3.批量删除:一条delete语句删除多条记录

DELETE FROM t_mobile_ownership WHERE id in (1,2)

xml代码示例:

<!-- 批量删除手机号归属地信息 -->
    <delete id="deleteBatch" parameterType="java.util.List">
    	DELETE FROM
    		t_mobile_ownership
    	WHERE
    		id IN
   		<foreach collection="mobileList" item="item" separator="," open="(" close=")">
   			#{item.id}
   		</foreach>
    </delete>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值