【问题标题】:Ensuring the order of columns returned in jdbctemplate确保 jdbctemplate 中返回的列的顺序
【发布时间】:2017-07-21 01:25:56
【问题描述】:

我正在尝试使用 JDBCTemplate 检索给定查询的地图列表。以下方法似乎适合我的用例:

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-

但是,我想确保对于给定的行,地图的顺序得到保证。即, A LinkedHashMap 会更好,因为我想保留列的顺序。有没有更好的方法来使用 JDBCTemplate 实现这一点?

【问题讨论】:

    标签: java spring jdbctemplate


    【解决方案1】:

    我认为使用自定义的 ColumnMapRowMapper 会为每一行创建一个 LinkedHashMap,然后将其传递给查询方法:

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

        RowMapper<Map<String, Object>> rowMapper = new ColumnMapRowMapper()
        {
            protected Map<String, Object> createColumnMap(int columnCount) 
            {
                return new LinkedHashMap<>(columnCount);
            }
        };
    
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
    
        String sql = "SELECT ...";      
    
        try
        {           
            List<Map<String,Object>> results = jdbcTemplate.query(sql, rowMapper);
            // ...
        }
        catch(DataAccessException e)
        {
            e.printStackTrace();
        }
    

    【讨论】:

      【解决方案2】:

      我自己在执行此操作时发现的有趣事实...如果您使用NamedParameterJdbcTemplate,无论如何都会更好,默认情况下将确保列顺序。

      例如,queryForList() 方法最终会创建一个 ColumnMapRowMapper():

      @Override
      public List<Map<String, Object>> queryForList(String sql, SqlParameterSource paramSource)
              throws DataAccessException {
      
          return query(sql, paramSource, new ColumnMapRowMapper());
      }
      

      在其实现中使用它:

          /**
           * 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);
          }
      

      链接的哈希映射将适当地保留排序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 2018-05-20
        相关资源
        最近更新 更多