Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JDBC - BeanPropertyRowMapper with Kotlin

Overview: The application deals with basic CRUD functionality for User information.

Issue: While reading user details from the pre-populated H2 database, I am facing issues while using BeanPropertyRowMapper. The mapper is not able to initialize the User instance as it is not able to use the default constructer of the data class.

Data Class:

enter image description here

Repository:

enter image description here

Error:

Caused by: java.lang.IllegalArgumentException: No argument provided for a required parameter: parameter #0 id of fun <init>(kotlin.String, kotlin.String, kotlin.String, kotlin.String, java.util.Date): org.chrysalis.userservice.model.User

Providing a specific rowmapper solves the issue, but I am confused why BeanPropertyRowMapper is not able to create the response.

enter image description here I am also wondering if this issue is just specific to the Java reflection and if this would be the same for other mapping utilities in spring.

like image 967
Dharmvir Tiwari Avatar asked Dec 11 '25 07:12

Dharmvir Tiwari


1 Answers

With the update to SpringFramework 5.3/SpringBoot 2.4, mapping by constructor call is now supported by the DataClassRowMapper.

https://spring.pleiades.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/DataClassRowMapper.html

I consider KRowMapper to have an advantage in terms of functionality, but if you don't feel the pain of using an external library, I recommend using DataClassRowMapper.


The following is an old answer.

Basically, the same thing happens with other tools.

The Java reflection tools initialize the instance with a no-arg constructor and then a setter to initialize the field. On the other hand, Kotlin's data class has no no-arg constructor and no setter (you can confirm this by decompiling).

So you need to define the field as a var and prepare the no-arg constructor or use Kotlin no-arg plugin (which breaks the null safety).

I also had trouble with the same situation, so I created a tool based on Kotlin reflection. Please use it if you like. https://github.com/ProjectMapK/KRowMapper

like image 126
wrongwrong Avatar answered Dec 13 '25 13:12

wrongwrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!