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

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)
使用Debug进行调试时,发现是在DataAccessUtils的requiredSingleResult()方法中抛出的异常。
源码如下:
[java] view plain copy
 
  1. public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {  
  2.         int size = (results != null ? results.size() : 0);  
  3.         if (size == 0) {  
  4.             throw new EmptyResultDataAccessException(1);  
  5.         }  
  6.         if (results.size() > 1) {  
  7.             throw new IncorrectResultSizeDataAccessException(1, size);  
  8.         }  
  9.         return results.iterator().next();  
  10.     }  

可以看出,当results为空时,就会抛出EmptyResultDataAccessException异常,Spring这样做的目的是为了防止程序员不对空值进行判断,保证了程序的健壮性。另外,当results的size大于1时,还会

当results的size大于1时,还会抛出IncorrectResultSizeDataAccessException异常,以保证返回的记录只有一条。
如果我们想查询结果为空时,返回null而不是抛出异常,该怎么办呢?
很简单,只需要在捕获EmptyResultDataAccessException,然后返回null,代码如下:
[java] view plain copy
 
  1. Object object = null;  
  2. try {  
  3.     object = jdbcTemplate.queryForObject();  
  4. catch (EmptyResultDataAccessException e) {  
  5.     return null;  
  6. }  
  7. return object;  
原文地址:https://www.cnblogs.com/guagua-join-1/p/8900266.html