Ensuring the order of columns returned in jdbctemplate

Viewed 1662

I'm trying to retrieve a list of Maps for a given query using JDBCTemplate. The following method seems to be apt for my use case:

public List<Map<String,Object>> queryForList(String sql)
                                      throws DataAccessException

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#queryForList-java.lang.String-

However, I want to make sure that for a given row, the Map's order is guaranteed. i.e, A LinkedHashMap would be better as I want to preserve the order of columns. Is there a better way to achieve this using JDBCTemplate?

2 Answers

Fun fact I just found while doing this myself... if you use a NamedParameterJdbcTemplate, which is better anyway, the column ordering will be ensured by default.

For example, the queryForList() method ends up creating a ColumnMapRowMapper():

@Override
public List<Map<String, Object>> queryForList(String sql, SqlParameterSource paramSource)
        throws DataAccessException {

    return query(sql, paramSource, new ColumnMapRowMapper());
}

Which uses this in its implementation:

    /**
     * Create a Map instance to be used as column map.
     * <p>By default, a linked case-insensitive Map will be created.
     * @param columnCount the column count, to be used as initial
     * capacity for the Map
     * @return the new Map instance
     * @see org.springframework.util.LinkedCaseInsensitiveMap
     */
    protected Map<String, Object> createColumnMap(int columnCount) {
        return new LinkedCaseInsensitiveMap<>(columnCount);
    }

The linked hash map will preserve ordering appropriately.

Related