获取每个Product的折扣ID,使用收集到的折扣ID列表,批量查询对应的折扣实体,将Product实体关联对应的折扣信息
List<Product> products = productRepository.findAll(specification);
// 检查查询结果是否为空
if (!products.isEmpty()) {
// 收集关联的折扣ID
List<Long> discountIds = products.stream()
.map(Product::getDiscountId)
.distinct()
.collect(Collectors.toList());
// 根据ID批量查询折扣实体
List<Discount> discounts = discountRepository.findAllByIds(discountIds);
// 将折扣实体列表转换为Map,优化后续匹配过程
Map<Long, Discount> discountMap = discounts.stream()
.collect(Collectors.toMap(Discount::getId, Function.identity()));
// 更新商品实体的折扣信息
for (Product product : products) {
Discount discount = discountMap.get(product.getDiscountId());
if (discount != null) {
product.setDiscountType(discount.getType());
product.setDiscountName(discount.getName());
}
}
}