After reading this article , I want to use Spring to stream the database query results directly to the JSON response to provide persistent memory (without eagerly loading the List in memory).
As in the article with Hibernate, I put together a greetingRepository object that returns a stream of database content based on JdbcTemplate . In this implementation, I create an iterator based on the requested ResultSet , and I return the stream as follows:
return StreamSupport.stream(spliterator(), false).onClose(() -> { log.info("Closing ResultSetIterator stream"); JdbcUtils.closeResultSet(resultSet); });
i.e. with the onClose() method, guaranteeing that the underlying ResultSet will be closed if the stream is declared in the try-with-resources construct:
try(Stream<Greeting> stream = greetingRepository.stream()) {
But, as in the article, I want this stream to be consumed by a custom object adapter (extended MappingJackson2HttpMessageConverter defined in the article). If we take try-with-resources aside, it can be done as follows:
@RequestMapping(method = GET) Stream<GreetingResource> stream() { return greetingRepository.stream().map(GreetingResource::new); }
However, as comments at the bottom of this article, it does not care about closing down core resources.
In the context of Spring MVC, how can I completely pass the JSON response from the database and still guarantee the closure of the ResultSet ? Could you give a specific solution?
source share