【问题标题】:What does JdbcTemplate do when RowMapper returns null?当 RowMapper 返回 null 时,JdbcTemplate 做了什么?
【发布时间】:2013-07-02 20:09:15
【问题描述】:

我正在使用JdbcTemplate.query(sql, args, rowMapper) 方法调用来返回对象列表。在某些情况下,我想跳过一行而不将其添加到我返回的列表中。在这些情况下,我想到了两种解决方案:

  1. 让 RowMapper 返回 null。
  2. 让 RowMapper 抛出异常(我知道 SQLExceptions 已处理,因此这是一种可能性)。

我的问题是:RowMapper.mapRow 返回 null 时,JdbcTemplate 是否将其添加到列表中?如果不是,我应该抛出一个 SQLException 吗?

【问题讨论】:

  • 不应该跳过一行是sql中where子句的责任吗?

标签: java spring jdbctemplate


【解决方案1】:

这是向结果列表添加行的代码

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;
    }
    ...

正如我们所见,它确实会添加 null。但是,除非存在错误,否则 RowMapper 没有理由返回 null。

【讨论】:

  • 即Spring JDBC中读取结果集,调用RowMapper,并将结果添加到输出列表的代码。显然,如果 RowMapper 返回 null,则 null 将被添加到列表中。由于ArrayList 允许null 元素,这将返回一个包含空值的列表。
【解决方案2】:

使用 RowMapper 填充后,您可以简单地从列表中删除 null。

rows = JdbcTemplate.query(sql, args, rowMapper);
rows.removeAll(Collections.singletonList(null));

【讨论】:

    【解决方案3】:

    当您返回 null 时,它确实会将此 null 添加到列表中,此外,如果您抛出 SQLException,它会“包装”在扩展 RuntimeException 的异常中,这样您就不必显式包含 try-catch 语句你不想。

    【讨论】:

    • 哦,所以 JdbcTemplate 处理任何 RuntimeException - 不仅仅是 SQLException?很高兴知道。
    • @ktm5124 我的意思是,抛出的任何 SQLException 都包含在一个我现在不记得其确切名称的异常中,但它扩展了 RuntimeException(不是已检查的异常),所以你不要不必输入额外的 try - catch
    • 您要查找的异常名称是 DataAccessException。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多