查询优化N+1
# 查询优化N+1
// 批量查询用户时,优化订单查询(避免 N+1)
public List<User> getUsersWithOrders(List<Long> userIds) {
// 1. 批量查主表:用户(1次查询)
List<User> users = userMapper.selectByIds(userIds);
if (CollectionUtils.isEmpty(users)) {
return Collections.emptyList();
}
// 2. 提取所有用户id,批量查关联表:订单(1次查询,替代 N 次查询)
List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
List<Order> orders = orderMapper.selectByUserIds(ids);
// 3. 手动组装数据(用 Map 优化匹配效率)
Map<Long, List<Order>> orderMap = orders.stream()
.collect(Collectors.groupingBy(Order::getUserId));
users.forEach(user -> user.setOrders(orderMap.getOrDefault(user.getId(), Collections.emptyList())));
return users;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Last Updated: 2025/12/02, 15:43:10