加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

返回Java 8流的Spring存储库方法不会关闭JDBC连接

发布时间:2020-12-14 05:59:28 所属栏目:Java 来源:网络整理
导读:我有一个 Spring数据存储库: @Repositoryinterface SomeRepository extends CrudRepositoryEntity,Long { StreamEntity streamBySmth(String userId);} 我在一些Spring bean中调用该方法: @Scheduled(fixedRate = 10000)private void someMethod(){ someRe
我有一个 Spring数据存储库:
@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 from Stream,则它可以正常工作.

更新:
Spring Boot版本是1.4.1.RELEASE

解决方法

作为 reference documentation clearly states,Streams需要与try-with-resources块一起使用.

此外,通过使用@Transactional注释周围的方法,确保在消耗流时保持(只读)事务处于打开状态.否则,将应用默认设置,并尝试在存储库方法返回时释放资源.

@Transactional
public void someMethod() {

  try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
    stream.forEach(…);
  } 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读