4.4.6 Stream处理查询结果

优质
小牛编辑
127浏览
2023-12-01

我们可以使用Stream作为返回类型可以对查询结果进行逐个处理。

Example 9. Stream the result of a query with Java 8 Stream(stream查询结果)

@Query("select u from User u")
Stream<User> findAllByCustomQueryAndStream();

Stream<User> readAllByFirstnameNotNull();

@Query("select u from User u")
Stream<User> streamAllPaged(Pageable pageable);

一个Stream中可能包含底层数据存储的特定资源,所以在使用后必须关闭。可以通过调用close()方法,也可以使用java 7中的try-with-resources块

Example 10. Working with a Stream result in a try-with-resources block(在块中使用Stream)

try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
  stream.forEach(…);
}

目前,不是所有的Spring Data模块都支持将Stream作为返回类型