Lithicas Lithicas - 2 years ago 221
Java Question

Spring JDBC - .queryForObject() returns too many results?

I have this SQL statement:

return jdbcTemplate.queryForObject("SELECT * FROM materials WHERE title = ?", new MaterialMapper(), title);

And since I'm using .queryForObject I'm expecting to just get one or no results back. Instead I'm getting more than 1 result back which throws the IncorrectResultSizeDataAccessException exception. Any ideas?

Answer Source

The method queryForObject(sql, rowMapper, args) (and all the overload) declare explicitely to throw an IncorrectResultSizeDataAccessException if the query returns more than 1 row, or does not return anything:

Throws: IncorrectResultSizeDataAccessException - if the query does not return exactly one row

In your case, since the query SELECT * FROM materials WHERE title = ? can return more than 1 row, you have two choices:

  • Either use the query(sql, rowMapper, args) method instead, which returns a List of elements and not just a single row. You can then use it to retrieve only the first element (if the list isn't empty).
  • Adjust your query so that it returns a single row by limiting the result.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download