README

利用Stream(流)处理查询结果

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

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

  1. @Query("select u from User u")
  2. Stream<User> findAllByCustomQueryAndStream();
  3. Stream<User> readAllByFirstnameNotNull();
  4. @Query("select u from User u")
  5. 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)

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

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