Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does JdbcTemplate do when RowMapper returns null?

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?

like image 601
ktm5124 Avatar asked Jul 02 '13 20:07

ktm5124


2 Answers

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.

like image 36
Evgeniy Dorofeev Avatar answered Oct 05 '22 07:10

Evgeniy Dorofeev


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));
like image 184
mathd Avatar answered Oct 05 '22 08:10

mathd