简体   繁体   中英

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?

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.

当你返回null然后它确实将这个null添加到列表中,同样,如果你抛出一个SQLException,它会被“包装”在扩展RuntimeException的Exception中,因为你不必显式包含try-catch语句我想。

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM