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.
log
is declared inside the companion object on line 46- Function
with
will help us to save some typing. Inside thewith
block, we can access all members ofjdbcTemplate
. splitUpNames
is 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
batchUpdate
is 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
.
jdbcOperations
returns a plainJdbcTemplate
if you still need to use itsources
is 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.
query
receives 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.