org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
使用template.queryForObject时发生异常
1 2 3 4 5 6 7 8 9 10 11
| @Nullable public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException { if (CollectionUtils.isEmpty(results)) { throw new EmptyResultDataAccessException(1); } else if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } else { return results.iterator().next(); } }
|
上面是nullableSingleResult方法中的源码,当results为空时,抛出EmptyResultDataAccessException
当返回值大小大于1时,抛出IncorrectResultSizeDataAccessException异常
所以在使用template.queryForObject时要进行异常处理
1 2 3 4 5 6 7 8 9 10 11
| public static User login(User loginuser) { String sql = "select * from user where username = ? and password = ?"; User resUser = null; try { resUser = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginuser.getUsername(), loginuser.getPassword()); return resUser; }catch (EmptyResultDataAccessException e) { return null; } }
|