Java8+JPAでSQL結果をStreamで返す方法

Java8+JPAでSQL結果をStreamで返す方法

Java8+JPAを使用してStreamを返すことが出来るようになりました。

try with resourceでcloseする必要があります。この方法がメモリ節約できるようです。

リストを返すメソッドやPageableでページングするよりもストリームを返す方がメモリ消費量、DB問い合わせ回数を減らすことが出来るようなので、処理も高速です。

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.

@Transactionalメソッド内でのみ使えます。

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

コメント

タイトルとURLをコピーしました