I have a SpringBoot application with a service that retrieves values from a database and passes them to a data model class. At the output, I want to get a list of data models with values from the database.
If I implement the service methods as follows, everything is fine. Here's an example of the method code:
public List<DataDto> getData() {
String sql = "EXAMPLE QUERY";
return jdbcTemplate.query(sql, (resultSet, idx) -> new DataDto(resultSet));
}
I would like to implement this using BeanPropertyRowMapper to avoid creating new instances of the DataDto class every time. I write the following code:
public List<DataDto> getData() {
String sql = "EXAMPLE QUERY";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DataDto.class));
}
When I try to execute this code, I get the error: NoSuchMethodException: api.rest.DataDto.().
The DataDto class is defined as follows:
@Data
public class DataDto {
private long param1;
private long param2;
private long param3;
public DataDto(ResultSet resultSet) {
try {
this.param1 = resultSet.getLong("PARAM_1");
this.param2 = resultSet.getLong("PARAM_2");
this.param3 = resultSet.getLong("PARAM_3");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Can you please suggest whether it is possible to implement this using BeanPropertyRowMapper?
I found in the documentation that in DataDto, it is recommended to use a parameterless constructor. However, I specifically need one that takes a ResultSet as input.