APNIC’s software team often come up with useful solutions to programming problems that they like to share with developers. In this post, APNIC’s Byron Ellacott shares a simple approach to expose the new techniques of Spring Framework’s JdbcTemplate, without exposing the costs of in-memory data caches or resource management.
Spring Framework’s JdbcTemplate is a workhorse of simple database access in a Spring application. However, it was designed in the days of Java 6, and doesn’t easily lend itself to modern techniques such as Java 8’s Stream API.
Here’s a simple approach to expose those new techniques, without exposing the costs of in-memory data caches or resource management.
The goals of the code are to offer the expressiveness of a Stream interface, without losing the resource management capabilities of JdbcTemplate or loading an entire result set into memory before processing it.
The code snippet below shows how the final implementation can be used.
In this case, the SQL statement itself could easily have done the filter expression, and could have done a DISTINCT select. But often the transformations to be done on an SQL query’s output are either difficult to do in SQL, or would require generation of moderately complex SQL on the fly.
Most developers are familiar with SQL, but few of us are experts in it. Using complex queries, trades performance for maintainability, and may be a premature optimisation.
The approach taken should be fairly obvious from this example. Rather than entirely avoiding the callback driven nature of JdbcTemplate with the benefits that brings, this approach simply invokes a stream inside the callback, and returns the stream’s results from the enclosing method.
The code implements Spring’s ResultSetExtractor interface, which is a Single Abstract Method (SAM) interface, allowing the use of a lambda expression to implement it.
The implementation wraps the SQL ResultSet in an iterator, constructs a stream using the Spliterators and StreamSupport utility classes, and applies that to a Function taking a stream of row sets and returning a generic result.
The end result is a simple way to use the Java 8 Stream API on SQL results in Spring Framework.
The views expressed by the authors of this blog are their own and do not necessarily reflect the views of APNIC. Please note a Code of Conduct applies to this blog.