• 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. }
  • 相关阅读:
    [IOS自动化]Xcode build时报错: Cannot link directly with dylib/framework
    echarts入门图表可视化(基本介绍+示例代码)
    Linux:进程控制
    LeetCode 389. 找不同
    ASIC/SOC的可测试性
    239. 奇偶游戏
    中间件上云部署 zookeeper
    又一个 Jupyter 神器,操作 Excel 自动生成 Python 代码
    SpringMVC执行流程-JSP模式
    Spark---核心介绍
  • 原文地址:https://blog.csdn.net/weixin_30342639/article/details/133365079