ResultData<List<PaymentOrderDTO>> resultData = paymentOrderBasicService.list(listDTO);
// 先对主表做分页查询
List<PaymentOrderDTO> resultDataData = resultData.getData();
// 获取主表 id 集合(10条)
List<Long> paymentOrderIds = resultDataData.stream().map(PaymentOrderDTO::getId).collect(Collectors.toList());
// 支付订单id 与 支付订单 关系map (后续 重排序有用)
Map<Long, PaymentOrderDTO> paymentOrderDTOMap = resultDataData.stream().collect(Collectors.toMap(PaymentOrderDTO::getId, v1 -> v1, (v1, v2) -> v2));
// 当 子表传入条件时
OrderListDTO selectOrderListDTO = listDTO.getOrderListDTO();
List<OrderDTO> orderDTOList = Collections.EMPTY_LIST;
//订单搜索
if (ObjectUtil.isNotEmpty(selectOrderListDTO)) {
selectOrderListDTO.setPage(null);
selectOrderListDTO.setIsPaymentFreight(BaseConstant.TRUE);
// 根据 上面分页后的 支付订单(主表)id集合(10条),做订单(子表)查询,以此来缩小查询范围
// 原先是直接查询所有订单信息
// 再去 in(所有的订单id)
// 再去做主表分页
// 但其实本次查询出所有订单id并没有作用,而且会导致sql拼接过长,10w+的订单id
selectOrderListDTO.setPaymentFreightIdList(paymentOrderIds);
// 由于主表与子表存在 1:N关系,所以 查询出相关订单(子表)(数量将大于等于10条)
// 但这里可以取到一个 较小的 订单集合,并且拥有排序
orderDTOList = orderBasicFeignService.list(selectOrderListDTO).getData();
if (ObjectUtil.isEmpty(orderDTOList)) {
return ResultData.SUCCESS(new ArrayList<>());
}
}
// 定义返回的结果集
ArrayList<PaymentOrderDTO> paymentOrderDTOList = new ArrayList<>();
// 这里对 子表结果集 做筛选并去重,即可拿到有序的 主表id集合(10条)
List<Long> sortedPaymentOrderIds = orderDTOList.stream().map(OrderDTO::getFreightPaymentOrderId).distinct().collect(Collectors.toList());
Map<Long, List<OrderDTO>> orderListMap = orderDTOList.stream().collect(Collectors.groupingBy(OrderDTO::getFreightPaymentOrderId));
sortedPaymentOrderIds.forEach(id -> {
// 这里遍历 拥有排序的集合,再去从 关系map 中取出对应的实体,
PaymentOrderDTO paymentOrderDTO = paymentOrderDTOMap.get(id);
// 放入有序集合中,这样即可保证,既拥有了 子表的排序,又不需要查询子表的所有id集合
paymentOrderDTOList.add(paymentOrderDTO);
});
关联子表条件查询时,不再 in 整个子表的id集合
于 2022-11-10 20:39:40 首次发布