Mysql大数据分组批量插入,并返回主键id

大数据量批量插入数据库主要问题是入库效率差,耗费时间长。解决该问题可以从几个方面思考,

  1. 合并插入的sql,多条insert语句合并成一条。
    如:一万条 insert into _table (,,…) value (,,…);
    合并 insert into _table (,,…) values (,,…),(,,…),(,,…)…;
  2. 控制提交到数据库的事务大小。
    mysql 默认是autocommit=on是默认开启自动提交事务,一条sql就会开启一个事务,虽然锁住数据较 少,但是数据库资源占用严重,对外提供操作性能急剧下降。
    当autocommit=off时,执行多条update(一千或者一万条时),只会开启一个事务,等到所有都update后,一并commit。这种情况会出现锁住数据较多,需要等待事务完成,外面的select进不来,大量连接等待获取行锁,同样影响数据库对外服务能力。
  3. 插入有序数据。

注意事项:
(1)SQL语句是有长度限制,在进行数据合并在同一SQL中务必不能超过SQL长度限制,通过max_allowed_packet配置可以修改,默认是1M,测试时修改为8M。

(2)事务需要控制大小,事务太大可能会影响执行的效率。MySQL有innodb_log_buffer_size配置项,超过这个值会把innodb的数据刷到磁盘中,这时,效率会有所下降。所以比较好的做法是,在数据达到这个这个值前进行事务提交。

请自测试:30万的数据量插入大概20秒左右,希望满足您的需求。
代码示例:
service类

Boolean insertBatch(List<StoreEntity> list);

serviceImpl类
由于我的实体比较大,防止批量插入sql大于1M,所以进行分组

 @Override
    public Boolean insertBatch(List<StoreEntity> list) {
        int i =0;
        int max = 10000;
        if(list.size() <= max){
            i = this.baseMapper.insertBatch(list);
        }else {
            //使用流遍历操作 每次插入10000条,防止批量插入sql大于1M
            int limit = (list.size() + max - 1) / max;
            List<List<StoreEntity>> mglist = new ArrayList<>();
            Stream.iterate(0, n -> n + 1).limit(limit).forEach(m -> {
                mglist.add(list.stream().skip(m * max).limit(max).collect(Collectors.toList()));
            });
            for (List<StoreEntity> entityList : mglist){
                i =   this.baseMapper.insertBatch(entityList);
            }

        }
        if(i > 0){
            return true;
        }
        return false;
    }

mapper类

int insertBatch(@Param("list") List<StoreEntity> list);

mapper.xml
设置useGeneratedKeys=“true” keyProperty="id"的作用是获取主键id

    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true" parameterType="java.util.List">
        insert into t_store (`id` ,
        `store_postion_code`, `store_postion_specs`,`store_postion_id` ,
        `store_area_code`,`store_area_id`,`store_area_name`,`store_area_shelf_code`,
        `goods_id`,`goods_code`,`goods_name`,`goods_specs`,`goods_unit`,
        `containers_id`,`containers_code`,
        `num`,`del`,`batch`,`team_id`,`task_id`,`created_time`,`updated_time`) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id,jdbcType=BIGINT},
            #{item.storePostionCode},
            #{item.storePostionSpecs},
            #{item.storePostionId,jdbcType=BIGINT},
            #{item.storeAreaCode},
            #{item.storeAreaId,jdbcType=BIGINT},
            #{item.storeAreaName},
            #{item.storeAreaShelfCode},
            #{item.goodsId,jdbcType=BIGINT},
            #{item.goodsCode},
            #{item.goodsName},
            #{item.goodsSpecs},
            #{item.goodsUnit},
            #{item.containersId,jdbcType=BIGINT},
            #{item.containersCode},
            #{item.num,jdbcType=INTEGER},
            #{item.del,jdbcType=INTEGER},
            #{item.batch},
            #{item.teamId,jdbcType=BIGINT},
            #{item.taskId,jdbcType=BIGINT},
            #{item.createdTime,jdbcType=TIMESTAMP},
            #{item.updatedTime,jdbcType=TIMESTAMP}
            )
        </foreach>
    </insert>

上述的实体的数据都是存在的,需要插入,如果想优化这个sql,或者满足自己想要的随机插入字段可以这么实现

<insert id="insertBatch" keyProperty="id" useGeneratedKeys="true" parameterType="java.util.List">
        insert into t_store
         <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="id != null">
        		id,
          </if>
          .
          .
          .
          </trim>
        values
        <foreach collection="list" item="item" index="index" separator=",">
        	(
            <if test="id != null">
	        	#{id,jdbcType=BIGINT},
	     	 </if>
	      	.
	      	.
	     	.
	      )
        </foreach>
    </insert>

希望您的问题得到解决,文章中如错误或不足,请指出,不胜感激,如有不足,请多多包含,也请各位大神能不吝赐教,抱拳

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值