What does JdbcTemplate do when RowMapper returns null?

ktm5124 picture ktm5124 · Jul 2, 2013 · Viewed 16.4k times · Source

I am using the JdbcTemplate.query(sql, args, rowMapper) method call to return a list of objects. There are some cases where I want to skip a row and not add it to the list that I return. In these cases, I've thought of two solutions:

  1. Have RowMapper return null.
  2. Have RowMapper throw an Exception (I know SQLExceptions are handled so this is one possibility).

My question is: When RowMapper.mapRow returns null, does JdbcTemplate add it to the list? If not, should I throw an SQLException instead?

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jul 2, 2013

This is the piece of code that adds rows to the result list

public class RowMapperResultSetExtractor<T> implements ResultSetExtractor<List<T>> {
    ...
    public List<T> extractData(ResultSet rs) throws SQLException {
        List<T> results = (this.rowsExpected > 0 ? new ArrayList<T>(this.rowsExpected) : new ArrayList<T>());
        int rowNum = 0;
        while (rs.next()) {
            results.add(this.rowMapper.mapRow(rs, rowNum++));
        }
        return results;
    }
    ...

as we can see it will really add null. However there is no reason why RowMapper should ever return null unless there is a bug in it.