spring-data-jpa-2.3.9 版本中,JpaRepository 的 findAllById(Iterable<ID> var1)
spring-data-jpa-2.3.9版本中JpaRepository的findAllById(IterableID var1)方法会根据传入的 ID 集合查询出所有匹配的实体并以ListT的形式返回。这个方法的行为很直接它等价于执行一个IN查询并且返回的 List 顺序与传入的 ID 顺序无关而是按照数据库查询结果的顺序。1. 方法定义javapublic interface JpaRepositoryT, ID extends PagingAndSortingRepositoryT, ID { ListT findAllById(IterableID ids); }2. 源码解析在spring-data-jpa-2.3.9中这个方法的底层实现是SimpleJpaRepository的findAllById方法。java// SimpleJpaRepository.java (Spring Data JPA 2.3.9) public ListT findAllById(IterableID ids) { if (ids null) { throw new IllegalArgumentException(The given Iterable of Ids must not be null!); } return this.getQuery(null, (Sort) null).setParameter(id, ids).getResultList(); }它生成的 SQL 大致如下sqlselect * from your_table where id in (?, ?, ?)3. 关键特性特性说明返回类型ListT查询不到匹配记录时返回空 List不是null顺序性返回的 List不保证与传入 ID 的顺序一致参数要求传入的IterableID不能为null但可以是空集合性能底层使用IN查询ID 集合过大时可能影响性能4. 返回顺序不一致的问题如果你需要按照传入 ID 的顺序返回结果不能直接依赖findAllById需要手动排序javapublic ListUser findAllByIdOrdered(ListLong ids) { // 查询结果 ListUser users userRepository.findAllById(ids); // 按传入 ID 顺序排序 MapLong, User userMap users.stream() .collect(Collectors.toMap(User::getId, Function.identity())); return ids.stream() .map(userMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); }5. 使用示例javaService public class UserService { Autowired private UserRepository userRepository; public ListUser getUsers() { // 1. 传入 List ListLong ids Arrays.asList(1L, 3L, 2L); ListUser users userRepository.findAllById(ids); // 返回顺序可能是 [1, 2, 3]按数据库默认排序不一定 [1, 3, 2] // 2. 传入 Set去重 SetLong idSet new HashSet(Arrays.asList(1L, 2L, 3L)); ListUser users2 userRepository.findAllById(idSet); // 3. 传入空集合 ListUser users3 userRepository.findAllById(Collections.emptyList()); // 返回空 List } }6. 注意事项注意点说明ID 不存在不存在的 ID 会被忽略不会报错参数为 null传入null会抛出IllegalArgumentException集合过大IN查询在 ID 过多时可能超出 SQL 长度限制或性能下降顺序如需按传入 ID 顺序返回需要额外处理7. 如果你想要“按 ID 顺序返回”javapublic ListUser findAllByIdOrdered(CollectionLong ids) { if (ids null || ids.isEmpty()) { return new ArrayList(); } // 1. 查询 ListUser users userRepository.findAllById(ids); // 2. 构建映射 MapLong, User userMap users.stream() .collect(Collectors.toMap(User::getId, Function.identity())); // 3. 按原顺序返回 return ids.stream() .map(userMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); }