EmptyResultDataAccessException:Spring的JdbcTemplate

  • Post author:
  • Post category:其他


问题描述:

在使用JdbcTemplate进行数据查询时,如果数据库中的数据不存在那么就会出现以下异常信息


Exception in thread "main" 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:812)

问提出现的原因

以下是spring中DataAccessUtils中出错的方法,当结果为null时就会抛出我们遇到的异常

public abstract class DataAccessUtils{
	    public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
        int size = results != null ? results.size() : 0;
        if (size == 0) {
            throw new EmptyResultDataAccessException(1);
        } else if (results.size() > 1) {
            throw new IncorrectResultSizeDataAccessException(1, size);
        } else {
            return results.iterator().next();
        }
    }
}

解决方法

捕获这个异常

    public User findUserByUserName(String username){
        User user = null;
        String sql = "select * from tab_user where username = ?";
        try {
            user =jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
        return user;
    }	



版权声明:本文为qq_40265485原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。