What does JdbcTemplate do when RowMapper returns null?
Asked Answered
N

3

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?

Nickienicklaus answered 2/7, 2013 at 20:9 Comment(1)
Shouldn't skipping a row(s) be the responsibility of the where clause in sql ?Naumachia
A
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.

Agincourt answered 2/7, 2013 at 20:16 Comment(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.Carnay
I
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));
Ironing answered 6/5, 2019 at 21:35 Comment(0)
A
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.

Amara answered 2/7, 2013 at 20:11 Comment(3)
Oh, so JdbcTemplate handles any RuntimeException - not just SQLException? Good to know.Nickienicklaus
@Nickienicklaus 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 - catchAmara
The name of the exception you're looking for is DataAccessException.Toxicant

© 2022 - 2024 — McMap. All rights reserved.