• MySQL分批插入/更新数据


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

            比如说现在有一个需要批量修改商品的方法,我们可以这么改造:

    1. public void batchUpdateById(List productList) {
    2. if (CollectionUtils.isEmpty(productList)) {
    3. return;
    4. }
    5. if (productList.size() > CommonUtils.BATCH_NUMBER) {
    6. int sizeNum = productList.size();
    7. int startNum = 0;
    8. int endNum = CommonUtils.BATCH_NUMBER - 1;
    9. while (startNum < endNum) {
    10. productMapper.batchUpdateById(productList.subList(startNum, endNum));
    11. startNum += CommonUtils.BATCH_NUMBER - 1;
    12. endNum += CommonUtils.BATCH_NUMBER - 1;
    13. if (endNum > sizeNum - 1) {
    14. endNum = sizeNum;
    15. }
    16. }
    17. } else {
    18. productMapper.batchUpdateById(productList);
    19. }
    20. }

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

            上面是我们自己手写的分批代码,而如果每个方法都这么写,也未免太过于繁琐了。这个时候我们就可以使用guava库中关于集合的partition分组方法来进行简化:

    1. @Override
    2. public void batchUpdateById(List list) {
    3. if (CollectionUtils.isEmpty(list)) {
    4. return;
    5. }
    6. List merchantGoodsSkuDOS = GoodsAnotherSkuConvertor.INSTANCE.goodsSkuBO2MerchantDOList(list);
    7. List> groupMerchantGoodsSkuDOS = Lists.partition(merchantGoodsSkuDOS, CommonUtils.BATCH_NUMBER);
    8. groupMerchantGoodsSkuDOS.forEach(goodsSkuMasterMapper::batchUpdateById);
    9. }

            由上可以看到,代码简化了很多(上面的goodsSkuBO2MerchantDOList方法只是将BO转成DO,和分组逻辑没有关系)。而对于批量查询的方法,我们也可以使用partition方法进行分组查询,防止in条件拼接太多的数据导致sql报错的情况出现:

    1. @Override
    2. public List listBySpuIdsSimple(List spuIds) {
    3. if (CollectionUtils.isEmpty(spuIds)) {
    4. return Collections.emptyList();
    5. }
    6. //去重
    7. spuIds = spuIds.stream().distinct().collect(Collectors.toList());
    8. List> groupSpuIds = Lists.partition(spuIds, CommonUtils.BATCH_NUMBER);
    9. List spuIdList = groupSpuIds.stream().map(goodsSkuMasterMapper::listBySpuIds).flatMap(Collection::stream)
    10. .collect(Collectors.toList());
    11. return GoodsAnotherSkuConvertor.INSTANCE.merchantGoodsSkuDO2GoodsSkuBOList(spuIdList);
    12. }
  • 相关阅读:
    byte buddy字节码增强——输出方法执行时间
    妙鸭相机功能代码复现
    数据结构基础学习
    诈骗分子投递“大闸蟹礼品卡”,快递公司如何使用技术手段提前安全预警?
    darknet 训练分类网络
    nginx代理socket链接集群后,频繁断开重连
    Python开发指南[2]之人脸模型训练与人脸识别
    Jest 如何支持异步及时间函数
    共谋韬略、共巢未来,电巢与韬略“战略合作签约仪式”圆满举办!
    甘特图组件DHTMLX Gantt示例 - 如何有效管理团队工作时间?(一)
  • 原文地址:https://blog.csdn.net/weixin_30342639/article/details/133365079