这是 queryForObject 方法源代码
@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws
DataAccessException {
List<T> results = this.query(sql, rowMapper);
return DataAccessUtils.nullableSingleResult(results);
}
DataAccessUtils.nullableSingleResult
@Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
throw new EmptyResultDataAccessException(1);
} else if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
} else {
return results.iterator().next();
}
}
不知道为什么他们在空集合上抛出异常,可能这只是上面方法的复制粘贴
public static <T> T requiredSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
throw new EmptyResultDataAccessException(1);
} else if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
} else {
return results.iterator().next();
}
}
比他们应该使用的方法多一步
@Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
return null;
} else if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
} else {
return results.iterator().next();
}
}
现在解决方案帮助了我:扩展 JdbcTemlate 类(您可以使用注入的 DataSource 构造它)并覆盖 queryForObject 方法:
@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = this.query(sql, rowMapper);
return DataAccessUtils.singleResult(results);
}
现在使用您的实现不要忘记检查它是否适用于春季版本更新(恕我直言不太可能)