Spring 5 was released last week with many exciting features, but for me, the most important one is the Kotlin support. Not only because I love the language but because I contributed to it. (I know, shameless plug)
One of the features included in this support is a set of extension functions for JdbcTemplate and MapSqlParamaterSource that gives you a more idiomatic API.
Let’s translate the Accessing Relational Data using JDBC with Spring official guide to Kotlin
Using Spring 5.0 JDBC
For this example, we’ll use Spring Boot 2.0 SNAPSHOT
Customer data class
Using JdbcTemplate
Let’s comment the most interesting lines.
logis declared inside the companion object on line 46- Function
withwill help us to save some typing. Inside thewithblock, we can access all members ofjdbcTemplate. splitUpNamesis aList<Pair<String, String>>. Later we’ll usePair’s destructuring declarations.- Inside any function that has a parameter type with destructuring declarations (
component1(),component2()and so on), you can replace it with them. In this case, we replacePair<String, String>with(String, String). - Last parameter of
batchUpdateis aParameterizedPreparedStatementSetter<T>which is a Java 8 functional interface. We can use functional interfaces in Kotlin as functions, including destructuring declarations. - This query is an extension function. It changes the order of parameters and switches
RowMapper<T>into a(ResultSet, Int) ->T. Because we aren’t using the last parameter (the row number), we can replace it with _
Speaking about extensions functions, you can check the kdoc here.
Using NamedParameterJdbcTemplate
NamedParameterJdbcTemplate is a version of JdbcTemplate that use named parameters (‘:parameter1’) instead of placeholders (‘?’). Spring 5 doesn’t provides any extension functions for NamedParameterJdbcTemplate (the API is good enough to use it from Kotlin) but it provides extension functions for a related class, MapSqlParameterSource.
jdbcOperationsreturns a plainJdbcTemplateif you still need to use itsourcesis aList<MapSqlParameterSource>- Extension function to set parameters in an array-like setter.
- There isn’t extension function to read with an array-like getter but we can add one easily.
- This insert query use named parameters.
queryreceives aMap<String, *>as a second parameters, very easy to use in Kotlin.
Conclusion
Spring JDBC with Kotlin provides a solid API for your relational database application. Enjoy.