Every Friday, we’re showing you a couple of nice new tutorial-style Java 8 features, which take advantage of lambda expressions, extension methods, and other great stuff. You’ll find the source code on GitHub.
Java 8 Goodie: Lambdas and SQL
If you’re used to writing Groovy, this may appear “so 2003” to you. We know. Groovy has known a very useful way to write string-based SQL since its early days. Here’s an example written in Groovy (see the official docs here):
Note also Groovy’s built-in String interpolation, where you can put expressions into strings. But we’re in Java land, and with Java 8, things get better in the Java / SQL integration as well, if we’re using third-party libraries, instead of JDBC directly.
In the following examples, we’re looking at how to fetch data from an H2 database and map records into custom POJOs / DTOs using these three popular libraries:
Things look just as nice when doing the same with Spring JDBC and RowMapper (note, the following still throws checked SQLExceptions):
new JdbcTemplate(
new SingleConnectionDataSource(c, true))
.query(sql, (rs, rowNum) ->
new Schema(
rs.getString("SCHEMA_NAME"),
rs.getBoolean("IS_DEFAULT")
))
.forEach(System.out::println);
… and if you’re using Apache DbUtils, you can do almost the same:
new QueryRunner()
.query(c, sql, new ArrayListHandler())
.stream()
.map(array -> new Schema(
(String) array[0],
(Boolean) array[1]
))
.forEach(System.out::println);
Conclusion
All three solutions are more or less equivalent and quite lean. The point here, again, is that Java 8 will improve all existing APIs. The more unambiguous (few overloads!) methods accepting SAM arguments (single abstract method types), the better for a Java 8 integration.
Java 8 and SQL look very lean
Next week, we’re going to see a couple of things that will greatly improve when using the java.util.Map API