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

前端 未结 2 1373
梦毁少年i
梦毁少年i 2021-02-20 04:51

I have a Spring data repository:

@Repository
interface SomeRepository extends CrudRepository {
    Stream streamBy         


        
相关标签:
2条回答
  • 2021-02-20 05:05

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

    0 讨论(0)
  • 2021-02-20 05:11

    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(…);
      } 
    }
    
    0 讨论(0)
提交回复
热议问题