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配置好,搞定
