我有一个 Spring data
存储库:
@Repository
interface SomeRepository extends CrudRepository<Entity, Long> {
Stream<Entity> streamBySmth(String userId);
}
我在一些 Spring bean 中调用该方法:
@Scheduled(fixedRate = 10000)
private void someMethod(){
someRepository.streamBySmth("smth").forEach(this::callSomeMethod);
}
我正在使用 MySQL 数据库。当我在一些成功的方法调用后运行应用程序时,它会抛出一个异常:
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
看来,Spring 没有正确关闭该连接。如果我已将方法返回值从 Stream
更改为 List
,它会正常工作。
更新: Spring Boot 版本为 1.4.1.RELEASE
最佳答案
作为reference documentation clearly states , Stream
需要与 try-with-resources block 一起使用。
此外,通过使用 @Transactional
注释周围的方法,确保在使用流时保持(只读)事务处于打开状态。否则,将应用默认设置并尝试在存储库方法返回时释放资源。
@Transactional
public void someMethod() {
try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
stream.forEach(…);
}
}
关于java - 返回 Java 8 流的 Spring 存储库方法不会关闭 JDBC 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015800/