myBatis 批量更新的方法

101 篇文章 2 订阅
	//MySQL 批量更新的方法	
	public void uptBatch(List<YourBean> beanList) {
        //批量更新的操作
        if (null != beanList && beanList.size() > 0) {
			// 每个批次条数 100 ,分批条数不能太大,防止sql过长导致更新失败的异常
            Integer partSize = Integer.parseInt(pSize);
            Integer size = beanList.size();
            // 判断是否有必要分批
            if (partSize < size) {
				// 批次数
                int part = size / partSize;
                System.out.println("共有 : " + size + "条,!" + " 分为 :" + part + "批");
                for (int i = 0; i < part; i++) {
                    // partSize 条
                    List<YourBean> subList = beanList.subList(0, partSize);
                    yourDao.batchUpdate(subList);
                    // 剔除
                    beanList.subList(0, partSize).clear();
                }
                if (!beanList.isEmpty()) {
					// 表示整除后的剩余项
                    yourDao.batchUpdate(beanList);
                }
            } else {
                yourDao.batchUpdate(beanList);
            }
        }
    }
	<update id="batchUpdate" parameterType="java.util.List">
        update t_yourtable
        <set> 
			column1 =
			<foreach collection="list" item="item" index="index"  separator=" " open="case id" close="end">
				when #{item.id} then #{item.name1}
			</foreach>
			,column2 =
			<foreach collection="list" item="item" index="index"  separator=" " open="case id" close="end">
				when #{item.id} then #{item.name2}
			</foreach>
        </set>
        <where>
            <choose>
                <when test="list != null and list.size() >0">
                    id in
                    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
                        #{item.id}
                    </foreach>
                </when>
                <otherwise>
                    id = ''
                </otherwise>
            </choose>
        </where>
    </update>

    //为了不影响原集合,可以新开辟集合去接收oldList
    List<YourBean> listNew  = new ArrayList<>();
    listNew.addAll(listOld.subList(0, listOld.size() - 1));

			<insert id="insertBatch" parameterType="java.util.List">
				insert into your_table
					(id,
					name,
					status)
				values
				<foreach collection="list" item="list" separator=",">
					( #{list.id},
					#{list.name},
					#{list.status})
				</foreach>
			</insert>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值