How to return SQL results in Stream with Java8+JPA

How to return SQL results in Stream with Java8+JPA

Stream can now be returned using Java8+JPA.

You need to close it with try with resource. This method seems to save memory.

Returning a stream seems to reduce memory consumption and the number of DB queries rather than paging with a method that returns a list or Pageable, so processing is also faster.

try (var emp = userRepository.findXxx()) {
  emp.forEach(System.out::println);
}

You’re trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction.

It can only be used within the @Transactional method.

@Transactional
public void findData() {
  try (var emp = userRepository.findData()) {
    emp.forEach(System.out::println);
  }
}

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL