0

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.......

vivek
  • 115
  • 2
  • 9
  • Is the 'invalid' value '2021-08-13' or is it something different. If the value is '2021-08-13', then your query seems to be wrong because it's not limitting the results correctly. A RowMapper maps a row into any object you want but it doesn't make sense to map the rows to a ModelRowMapper. It should be `ModelRowMapper implements RowMapper` where model is your domain object. Have a look at this [tutorial](https://www.tutorialspoint.com/springjdbc/springjdbc_rowmapper.htm). – The Frozen One Aug 20 '21 at 16:24

1 Answers1

0

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"));
       }
      });
    }
Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17