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
For this example, we’ll use Spring Boot 2.0 SNAPSHOT
Let’s comment the most interesting lines.
log
is declared inside the companion object on line 46with
will help us to save some typing. Inside the with
block, we can access all members of jdbcTemplate
.splitUpNames
is a List<Pair<String, String>>
. Later we’ll use Pair
’s destructuring declarations.component1()
, component2()
and so on), you can replace it with them. In this case, we replace Pair<String, String>
with (String, String)
.batchUpdate
is a ParameterizedPreparedStatementSetter<T>
which is a Java 8 functional interface. We can use functional interfaces in Kotlin as functions, including destructuring declarations.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.
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
.
jdbcOperations
returns a plain JdbcTemplate
if you still need to use itsources
is a List<MapSqlParameterSource>
query
receives a Map<String, *>
as a second parameters, very easy to use in Kotlin.Spring JDBC with Kotlin provides a solid API for your relational database application. Enjoy.