• 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. }
  • 相关阅读:
    【毛毛讲书】【混合信号】如何更好地设计激励措施?
    AutoCAD Electrical 2022—源箭头和目标箭头
    STM32配置看门狗
    “银行家算法”大揭秘!在前端表格中利用自定义公式实现“四舍六入五成双”
    计算机专业本科毕业生个人学习总结
    chatGPT底层原理是什么,为什么chatGPT效果这么好?三万字长文深度剖析-下
    jmeter JDBC Request参数化
    沉浸式推理乐趣:体验线上剧本杀小程序的魅力
    APP产品经理岗位的具体内容(合集)
    手搭手Ajax经典基础案例省市联动
  • 原文地址:https://blog.csdn.net/weixin_30342639/article/details/133365079