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

大城市里の小女人 提交于 2020-08-02 06:33:42

问题


I have a Spring data repository:

@Repository
interface SomeRepository extends CrudRepository<Entity, Long> {
    Stream<Entity> streamBySmth(String userId);
}

I am calling that method in some Spring bean:

@Scheduled(fixedRate = 10000)
private void someMethod(){
    someRepository.streamBySmth("smth").forEach(this::callSomeMethod);
}

I am using MySQL database. And when I am running application after some successful method invocations it throws an exception:

o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 08001
o.h.engine.jdbc.spi.SqlExceptionHelper   : Could not create connection to database server.
o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

org.springframework.dao.DataAccessResourceFailureException: Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

It seems, that connection was not closed properly by Spring. If I have changed method return value to List from Stream it works correctly.

UPDATE: Spring Boot version is 1.4.1.RELEASE


回答1:


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(…);
  } 
}



回答2:


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



来源:https://stackoverflow.com/questions/41015800/spring-repository-method-which-are-returning-java-8-stream-doesnt-close-jdbc-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!