11

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?

ktm5124
  • 11,861
  • 21
  • 74
  • 119

3 Answers3

8

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    That is the code in Spring JDBC that reads the resultset, calls the RowMapper, and adds the result to the output list. Clearly, if the RowMapper returns null, null will be added to the list. Since `ArrayList` permits `null` elements, this will return a list with nulls in it. – Jim Garrison Jul 02 '13 at 20:29
3

You can simply remove the null from the list after populating with the RowMapper.

rows = JdbcTemplate.query(sql, args, rowMapper);
rows.removeAll(Collections.singletonList(null));
mathd
  • 2,415
  • 2
  • 17
  • 8
1

When you return null then it indeed adds this null to the list, also, if you throw an SQLException it is "wrapped" in a Exception that extends RuntimeException, for you not to have to include explicitly a try-catch statement if you don't want to.

morgano
  • 17,210
  • 10
  • 45
  • 56
  • Oh, so JdbcTemplate handles any RuntimeException - not just SQLException? Good to know. – ktm5124 Jul 02 '13 at 20:14
  • @ktm5124 What i meant to say is that any SQLException thrown is wrapped in an exception whose exactly name I can't remember right now, but it extends RuntimeException (not a checked exception) so you don't have to type extra try - catch – morgano Jul 02 '13 at 20:17
  • The name of the exception you're looking for is DataAccessException. – Gustavo Guevara May 26 '15 at 21:35