javaspring-bootjava-14java-record

No default constructor found with Java record and BeanPropertyRowMapper


I am playing with the new Java 14 and Spring Boot. I have used the new cool record instead of a regular Java class for data holders.

public record City(Long id, String name, Integer population) {}

Later in my service class, I use Spring BeanPropertyRowMapper to fetch data.

@Override
public City findById(Long id) {
    String sql = "SELECT * FROM cities WHERE id = ?";
    return jtm.queryForObject(sql, new Object[]{id},
            new BeanPropertyRowMapper<>(City.class));
}

I end up with the following error:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zetcode.model.City]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.zetcode.model.City.<init>()
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]

How to add a default constructor for a record or is there any other way to fix this?


Solution

  • You can use DataClassRowMapper. It works fine with records.

    @Override
    public City findById(Long id) {
        String sql = "SELECT * FROM cities WHERE id = ?";
        return jtm.queryForObject(sql, new DataClassRowMapper<>(City.class), id);
    }