代码之家  ›  专栏  ›  技术社区  ›  ajc

从数据库中提取数据并构造自定义json

  •  0
  • ajc  · 技术社区  · 6 年前

    我有一个包含如下示例数据的表->

    column1 column2 
    1       A
    1       B
    2       C
    2       D
    

    我想创建一个返回此的端点->

    {
      "1" : {
        "column1": "1"
        "column2": [A, B]
      },
      "2" : {
        "column1": "2"
        "column2": [C, D]
      }
    }
    

    处理这个问题最有效的方法是什么?

    我目前的做法:

    1. select * from table. //this.jdbcTemplate.queryForList(sql)
    2. 迭代和构造任何需要的暴力。

      public Map formatData(List data) {
         // iterating over the list and logic to construct the required map.
      }
      
    1 回复  |  直到 6 年前
        1
  •  0
  •   Traian GEICU    6 年前

    可以对迭代查询结果进行一些调整。


    1使用 select distinct(c1) from t
    2使用 select distinct(c2) from t where t.c1=key 论直接迭代抓取值 * 地点和条件

    public Map formatData(List keys) {
    // iterating over the list and logic to construct the required map.
        for(String key:keys)
        {
             List values = query_2(key);
             map.put(key, values)
        }
    }
    

    由于只从db中获取“最终结果”(不使用java代码中的outprocess作为原始列表),所以它可能会更快,但应该检查它。