Since returning a null when there is no data is something I want to do often when using queryForObject I have found it useful to extend JdbcTemplate and add a queryForNullableObject method similar to below.
public class JdbcTemplateExtended extends JdbcTemplate {
public JdbcTemplateExtended(DataSource datasource){
super(datasource);
}
public <T> T queryForNullableObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, rowMapper);
if (results == null || results.isEmpty()) {
return null;
}
else if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
else{
return results.iterator().next();
}
}
public <T> T queryForNullableObject(String sql, Class<T> requiredType) throws DataAccessException {
return queryForObject(sql, getSingleColumnRowMapper(requiredType));
}
}
You can now use this in your code the same way you used queryForObject
String result = queryForNullableObject(queryString, String.class);
I would be interested to know if anyone else thinks this is a good idea?