JdbcTemplate中queryForObject⽅法返回空结果或不正确结果
数量的解决⽅法
在使⽤Spirng提供的JdbcTemplate中名为queryForObject API进⾏数据库查询时有时会抛出如下异常:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
(不正确的结果⼤⼩,预期是1,实际为0)
或者:
org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 2
(不正确的结果⼤⼩,预期是1,实际为2)
在解决这些异常之前,我们⾸先来看看queryForObject API的源代码,假设我们调⽤的是queryForObject(String sql,Class requiredType)。JdbcTemplate.class
1public <T> T queryForObject(String sql, Class<T> requiredType)
2throws DataAccessException
3 {return queryForObject(sql, getSingleColumnRowMapper(requiredType));}
4
5public <T> T queryForObject(String sql, RowMapper<T> rowMapper)
6throws DataAccessException {
7 List<T> results = query(sql, rowMapper);
quiredSingleResult(results);
9 }
10
11public <T> List<T> query(String sql, RowMapper<T> rowMapper)
12throws DataAccessException {
13return query(sql, new RowMapperResultSetExtractor<T>(rowMapper));
14 }
15
16public <T> T query(final String sql, final ResultSetExtractor<T> rse)
17throws DataAccessException {
jdbctemplate查询一条数据18 Null(sql, "SQL must not be null");
19 Null(rse, "ResultSetExtractor must not be null");
20if (logger.isDebugEnabled()) {
21 logger.debug("Executing SQL query [" + sql + "]");
22 }
23class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
24public T doInStatement(Statement stmt) throws SQLException {
25 ResultSet rs = null;
26try {
27 rs = uteQuery(sql);
28 ResultSet rsToUse = rs;
29if (nativeJdbcExtractor != null) {
30 rsToUse = NativeResultSet(rs);
31 }
actData(rsToUse);
33 }
34finally {
35 JdbcUtils.closeResultSet(rs);
36 }
37 }
38public String getSql() {
39return sql;
40 }
41 }
42return execute(new QueryStatementCallback());
43 }
DataAccessUtil.class
1public static <T> T requiredSingleResult(Collection<T> results)
2throws IncorrectResultSizeDataAccessException {
3int size = (results != null ? results.size() : 0);
4if (size == 0) {
5throw new EmptyResultDataAccessException(1);
6 }
7if (results.size() > 1) {
8throw new IncorrectResultSizeDataAccessException(1, size);
9 }
10return results.iterator().next();
11 }
通过阅读源代码,可以清楚地看到在DataAccessUtils.class中requiredSingleResult⽅法中,当结果集合的size为0或者⼤于1时,就会抛出以上两个异常。
解决⽅法有两个:
(1)通过修改数据库:删除数据库中对应名称(column)相同的记录,留下只剩"1"条。 (2)通过更换⽅法:使⽤query⽅法返回list对象(该⽅法能返回所有查询记录)
1public transient List query(String sql, RowMapper rowMapper, Object args[])
2throws DataAccessException
3 {
4return (List)query(sql, args, ((ResultSetExtractor) (new RowMapperResultSetExtractor(rowMapper))));
5 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论