MongoRepository调用findAllById时如何在缺少匹配ID时抛出异常
解决方案
你只需要单次查询全量匹配的批次后,做内存层面的ID校验即可,不需要多次查询数据库,实现逻辑如下:
// batchIdList为从传入列表中提取的所有batchId集合 List<Batch> existingBatches = batchRepository.findAllById(batchIdList); // 提取已查到的批次ID集合 Set<Long> existIdSet = existingBatches.stream() .map(Batch::getBatchId) .collect(Collectors.toSet()); // 筛选所有不存在的ID List<Long> notFoundIds = batchIdList.stream() .filter(id -> !existIdSet.contains(id)) .collect(Collectors.toList()); // 存在未匹配ID时直接抛出异常 if (!notFoundIds.isEmpty()) { throw new ResourceNotFoundException("批次ID不存在:" + notFoundIds); } // 校验通过后正常执行更新逻辑 existingBatches.forEach(existingBatch -> { // 用新的itemList数据更新existingBatch });
这种实现的优势:
- 全程仅触发1次MongoDB查询请求,不会产生多余的数据库IO
- 可以直接返回所有不存在的批次ID,报错信息更直观,方便接口调用方定位问题
内容的提问来源于stack exchange,提问作者Ishara M
相关产品推荐
相关产品推荐

