Edu*_*nko 8 java spring spring-jdbc spring-data java-stream
我有一个Spring data存储库:
@Repository
interface SomeRepository extends CrudRepository<Entity, Long> {
Stream<Entity> streamBySmth(String userId);
}
Run Code Online (Sandbox Code Playgroud)
我在一些Spring bean中调用该方法:
@Scheduled(fixedRate = 10000)
private void someMethod(){
someRepository.streamBySmth("smth").forEach(this::callSomeMethod);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用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
Run Code Online (Sandbox Code Playgroud)
看来,Spring没有正确关闭连接.如果我已经将方法返回值更改为List从Stream它正常工作.
更新: Spring Boot版本是1.4.1.RELEASE
Oli*_*ohm 11
正如参考文档明确指出的那样,Streams需要与try-with-resources块一起使用.
此外,通过使用注释周围方法,确保在消耗流时保持(只读)事务处于打开状态@Transactional.否则,将应用默认设置,并尝试在存储库方法返回时释放资源.
@Transactional
public void someMethod() {
try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
stream.forEach(…);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6095 次 |
| 最近记录: |