欢迎投稿

今日深度:

MySQL分批插入/更新数据方式,

MySQL分批插入/更新数据方式,


目录
  • MySQL分批插入/更新数据
    • 比如说现在有一个需要批量修改商品的方法
    • 由上可以看到,代码简化了很多
  • 总结

    MySQL分批插入/更新数据

    在我们的日常开发中,经常会使用到批量insert/update的语句来实现相关的业务功能。而如果数据量比较大的话,会导致sql语句更新失败、抛出异常的情况出现。

    这个时候我们可以批量执行sql语句,一批一批的执行。

    比如说现在有一个需要批量修改商品的方法

    我们可以这么改造:

    public void batchUpdateById(List<Product> productList) {
        if (CollectionUtils.isEmpty(productList)) {
            return;
        }
    
        if (productList.size() > CommonUtils.BATCH_NUMBER) {
            int sizeNum = productList.size();
            int startNum = 0;
            int endNum = CommonUtils.BATCH_NUMBER - 1;
            while (startNum < endNum) {
                productMapper.batchUpdateById(productList.subList(startNum, endNum));
                startNum += CommonUtils.BATCH_NUMBER - 1;
                endNum += CommonUtils.BATCH_NUMBER - 1;
                if (endNum > sizeNum - 1) {
                    endNum = sizeNum;
                }
            }
        } else {
            productMapper.batchUpdateById(productList);
        }
    }

    上面BATCH_NUMBER的值是50,意味着当修改商品的数量大于50的时候,会以50个数据为一批,分批的执行;而如果修改商品的数量不大于50的时候,就直接一次执行就够了。

    上面是我们自己手写的分批代码,而如果每个方法都这么写,也未免太过于繁琐了。

    这个时候我们就可以使用guava库中关于集合的partition分组方法来进行简化:

    @Override
    public void batchUpdateById(List<GoodsSkuBO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
    
        List<MerchantGoodsSkuDO> merchantGoodsSkuDOS = GoodsAnotherSkuConvertor.INSTANCE.goodsSkuBO2MerchantDOList(list);
        List<List<MerchantGoodsSkuDO>> groupMerchantGoodsSkuDOS = Lists.partition(merchantGoodsSkuDOS, CommonUtils.BATCH_NUMBER);
        groupMerchantGoodsSkuDOS.forEach(goodsSkuMasterMapper::batchUpdateById);
    }

    由上可以看到,代码简化了很多

    (上面的goodsSkuBO2MerchantDOList方法只是将BO转成DO,和分组逻辑没有关系)。

    而对于批量查询的方法,我们也可以使用partition方法进行分组查询,防止in条件拼接太多的数据导致sql报错的情况出现:

    @Override
    public List<GoodsSkuBO> listBySpuIdsSimple(List<Long> spuIds) {
        if (CollectionUtils.isEmpty(spuIds)) {
            return Collections.emptyList();
        }
    
        //去重
        spuIds = spuIds.stream().distinct().collect(Collectors.toList());
        List<List<Long>> groupSpuIds = Lists.partition(spuIds, CommonUtils.BATCH_NUMBER);
        List<MerchantGoodsSkuDO> spuIdList = groupSpuIds.stream().map(goodsSkuMasterMapper::listBySpuIds).flatMap(Collection::stream)
                .collect(Collectors.toList());
        return GoodsAnotherSkuConvertor.INSTANCE.merchantGoodsSkuDO2GoodsSkuBOList(spuIdList);
    }

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持PHP之友。

    您可能感兴趣的文章:
    • MySQL数据库中的UPDATE(更新数据)详解
    • 大批量数据用mysql批量更新数据的4种方法总结
    • MySQL数据库操作DML 插入数据,删除数据,更新数据
    • MySQL并发更新数据时的处理方法
    • Mysql动态更新数据库脚本的示例讲解

    www.htsjk.Com true http://www.htsjk.com/Mysql/48635.html NewsArticle MySQL分批插入/更新数据方式, 目录 MySQL分批插入/更新数据 比如说现在有一个需要批量修改商品的方法 由上可以看到,代码简化了很多 总结 MySQL分批插入/更新数据 在我们的日常开发中...
    评论暂时关闭