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

前端 未结 2 1399
梦毁少年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: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 stream = repository.findAllByCustomQueryAndStream()) {
        stream.forEach(…);
      } 
    }
    

提交回复
热议问题