org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

来源:互联网 发布:春晓软件注册码 编辑:程序博客网 时间:2024/06/08 11:55
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0    at org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:71)    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:732)    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:747)

解决办法就是捕捉这个异常然后返回当没有这条数据需用它替换的值即可。一般设置为null,这个无数据的返回值依需求而定。

String sql = "select tt from aa where bb=? and cc=?";        Object[] params = { bb, cc};        Double value = 0.0;        try {            value = this.getJdbcTemplate().queryForObject(sql, params,                    Double.class);        } catch (EmptyResultDataAccessException e) {            value = 1.0;        }

queryForMap,queryForLong,queryForInt…都可以依照此方法。

另一种方法是将查询出的0行,或者null的数据,转换成0,这种方法可以比较以下3条sql语句。

SELECT xxx FROM bendi where region_code=0 and ddate='201502';SELECT sum(xxx) FROM bendi where region_code=0 and ddate='201502';SELECT IFNULL(sum(xxx),0) FROM bendi where region_code=0 and ddate='201502';
0 0