【异常】EmptyResultDataAccessException:Incorrect result size: expected 1,actual 0

在使用JdbcTemplate的queryForMap方法,查询数据库时报错。

原因:

查看源码:
"JdbcTemplate"类

public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
	return queryForObject(sql, args, argTypes, getColumnMapRowMapper());
}

public Map<String, Object> queryForMap(String sql, Object... args) throws DataAccessException {
	return queryForObject(sql, args, getColumnMapRowMapper());
}

public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
	List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
	return DataAccessUtils.requiredSingleResult(results);
}

public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args) throws DataAccessException {
	List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
	return DataAccessUtils.requiredSingleResult(results);
}

"DataAccessUtils"类

/**
* Return a single result object from the given Collection.
 * 

Throws an exception if 0 or more than 1 element found. * @param results the result Collection (can be null) * @return the single result object * @throws IncorrectResultSizeDataAccessException if more than one * element has been found in the given Collection * @throws EmptyResultDataAccessException if no element at all * has been found in the given Collection */ 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(); }

根据源码得知,使用queryForMap方法或queryForObject方法查询数据库时,如果结果集为空,则会抛出"EmptyResultDataAccessException"异常。如果结果集数量多于1个,则会抛出"IncorrectResultSizeDataAccessException"异常。

解决办法:

添加try/catch,捕获异常

你可能感兴趣的:(Oracle,spring)