Rowmapper vs ResultSetExtractor in spring

739 Views Asked by At

I'm facing weird issue with Spring jdbc RowMapper:-

Here is my code

public void test(){
 String sql=" Query  will fetch records where dateColumn<='2021-08-17' Limit 1";
 jdbcTemplate.query(sql, new ModelRowMapper());
}

public class ModelRowMapper implements RowMapper<ModelRowMapper> {
    @Override
    public ModelRowMapper mapRow(ResultSet rs, int rowNum) throws SQLException {
     ModelRowMapper model= new ModelRowMapper();
     System.out.println(rs.getString("value"));

  }
}

Example:-

db records:-
2021-08-21
2021-08-15
2021-08-13

Output I'm expecting is 2021-08-15

In the ModelRowMapper class observed resultSet prints two values(1st is valid:- 2021-08-15) then print the invalid value and in the response also I will be getting invalid value

But above query properly works when I use the ResultSetExtractor

jdbcTemplate.query(sql, new ResultSetExtractor<String>() {
    @Override
    public String extractData(ResultSet rs) throws SQLException, DataAccessException {
        while (rs.next()) {
           System.err.println(rs.getString("value"));
        }
        //prints only one value and returns the same value
        return "";
    }
});

What would be the issue with rowMapper?.... Any suggestions would be helpful.......

1

There are 1 best solutions below

0
On

You are somehow misunderstood how rowmapper should be called! use the following syntax, that would give you the desired result.

    public void test(){
       String sql=" Query  will fetch records where dateColumn<='2021-08-17' Limit 1";
       jdbcTemplate.query(query, new RowMapper<ModelRowMapper>(){
        @Override
        public ModelRowMapper mapRow(ResultSet rs, int rowNum) throws 
        SQLException {
              ModelRowMapper model= new ModelRowMapper();
              System.out.println(rs.getString("value"));
       }
      });
    }