Spring中使用JdbcTemplate的queryForObject方法,当查不到数据时会抛出如下异常:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
org.springframework.dao.support.DataAccessUtils.(DataAccessUtils.java:71)
org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:729)
查看DataAccessUtils的源码,找到requiredSingleResult方法:
public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
int size = (results != null ? results.size() : 0);
if (size == 0) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, size);
}
return results.iterator().next();
}
发现当查询的result为空时,size赋值为0,并抛出EmptyResultDataAccessException异常,此为原因所在。猜测Spring这样设计可能是为了防止用户不对空值做出判断,保证了程序的健壮性。同时,当results的size大于1时同样会抛出异常,以保证返回单一的Object。