【异常】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.
 * <p>Throws an exception if 0 or more than 1 element found.
 * @param results the result Collection (can be <code>null</code>)
 * @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,捕获异常

展开阅读全文
©️2020 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值