解决Spring JdbcTemplate调用queryForObject()方法结果集为空时报异常
JdbcTemplate用的时候发现一个问题:
调用queryForObject()方法,如果没有查到东西则会抛一个异常:org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
不希望抛出此异常,而是返回为null就行了。
public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
源码中结果集返回调用了
DataAccessUtils的一个静态方法,在这个静态方法中spring做了判断:
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(); }
直接继承JdbcTemplate,重写queryForObject()方法,结果集==0的时候,return null;
public class IJdbcTemplate extends JdbcTemplate{ @Override public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException { List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1)); return IDataAccessUtils.requiredSingleResult(results); } }
public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { return null; } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, size); } return results.iterator().next(); }
将自己的IJdbcTemplate配置好,搞定