Spring中EmptyResultDataAccessException异常的处理方法

        Spring中使用JdbcTemplate的queryForObject方法,当查不到数据时会抛出如下异常:

 
	org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
	org.springframework.dao.support.DataAccessUtils.(DataAccessUtils.java:71)
	org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:729)

        查看DataAccessUtils的源码,找到requiredSingleResult方法:

	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();
 	}

        发现当查询的result为空时,size赋值为0,并抛出EmptyResultDataAccessException异常,此为原因所在。猜测Spring这样设计可能是为了防止用户不对空值做出判断,保证了程序的健壮性。同时,当results的size大于1时同样会抛出异常,以保证返回单一的Object。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值