Spring repository method which are returning Java 8 stream doesn't close JDBC connection

As the reference documentation clearly states, Streams need to be used with a try-with-resources block.

Also, make sure you keep a (read-only) transaction open for the time of the consumption of the stream by annotating the surrounding method with @Transactional. Otherwise the default settings apply and the resources are attempted to be freed on repository method return.

@Transactional
public void someMethod() {

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

Using @Transactional(readOnly = true) and public access modifier will solve the issue. Any other access modifier will not work.