java 当 RowMapper 返回 null 时,JdbcTemplate 会做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17434936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does JdbcTemplate do when RowMapper returns null?
提问by ktm5124
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:
我正在使用JdbcTemplate.query(sql, args, rowMapper)
方法调用来返回对象列表。在某些情况下,我想跳过一行而不将其添加到我返回的列表中。在这些情况下,我想到了两种解决方案:
- Have RowMapper return null.
- Have RowMapper throw an Exception (I know SQLExceptions are handled so this is one possibility).
- 让 RowMapper 返回 null。
- 让 RowMapper 抛出一个异常(我知道处理 SQLExceptions 所以这是一种可能性)。
My question is: When RowMapper.mapRow
returns null, does JdbcTemplate add it to the list? If not, should I throw an SQLException instead?
我的问题是:当RowMapper.mapRow
返回 null 时,JdbcTemplate 是否将其添加到列表中?如果没有,我应该抛出 SQLException 吗?
采纳答案by Evgeniy Dorofeev
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。然而,除非存在错误,否则 RowMapper 没有理由应该返回 null。
回答by mathd
You can simply remove the null from the list after populating with the RowMapper.
使用 RowMapper 填充后,您可以简单地从列表中删除空值。
rows = JdbcTemplate.query(sql, args, rowMapper);
rows.removeAll(Collections.singletonList(null));
回答by morgano
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.
当您返回 null 时,它确实会将此 null 添加到列表中,此外,如果您抛出 SQLException,它会“包装”在扩展 RuntimeException 的异常中,因为如果您不这样做,则不必显式包含 try-catch 语句不想。