This is queryForObject method source code
@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws
DataAccessException {
List<T> results = this.query(sql, rowMapper);
return DataAccessUtils.nullableSingleResult(results);
}
DataAccessUtils.nullableSingleResult
@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();
}
}
dunno why they throw exception on empty collection, probably this is just a copy-paste from method above
public static <T> T requiredSingleResult(@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();
}
}
One more step above the method they shoult have used
@Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
return null;
} else if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
} else {
return results.iterator().next();
}
}
NOW SOLUTION helped me:
Extend JdbcTemlate class (you can construct it with DataSource injected)
and overrride the queryForObject method:
@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = this.query(sql, rowMapper);
return DataAccessUtils.singleResult(results);
}
now work with your implementation
Don't forget to check if it works on spring version update (very unlikely IMHO)