如何使用Java有效地分组SQL查询输出?

时间:2016-12-30 18:04:01

标签: java hashmap

我在三个不同的表上使用核心Java进行SQL查询,使用LEFT连接并获得以下输出:

pId  pName  sId  sName  gId  gName
1    p1     11   s1     111  g1
1    p1     11   s1     112  g2
2    p2     12   s2     null null
3    p3     13   s3     113  g3

现在我想将其分组如下:

[{
    "pId": 1,
    "pname": "p1",
    "sub": [{
        "sId": 11,
        "sName": "s1",
        "grades": [{
            "gId": 111,
            "gName": "g1"
        }, {
            "gId": 112,
            "gName": "g2"
        }]
    }]
}, {
    "pId": 2,
    "pname": "p2",
    "sub": [{
        "sId": 12,
        "sName": "s2",
        "grades": []
    }]
}, {
    "pId": 3,
    "pname": "p3",
    "sub": [{
        "sId": 13,
        "sName": "s3",
        "grades": [{
            "gId": 113,
            "gName": "g3"
        }]
    }]
}]

要按上述输出对此进行分组,我在Java代码中执行以下过程:

  

1)迭代所有pId

     

2)迭代pId中的所有sId

     

3)迭代sId中的所有gId

这需要花费大量时间来执行并获得所需的输出。

有没有办法以最少的迭代以更快的方式完成它?

非常感谢任何帮助/解决方法。

我在pId上尝试过hashmap但仍无法找到解决方案

2 个答案:

答案 0 :(得分:1)

创建一个对象,如下所示

 public class Process{

        // getters and setters
        private int pid;

        // getters and setters
        private String pName;

        // getters and setters
        private List<SubProcess> subList;

        // override equals and hashcode basd on process name and id 

    }

    public class SubProcess{

       // getters and setters
       private int subProcessId;
        // getters and setters
        private String subProcessName;
        // getters and setters
        private List<Grade> gradeList;

        // override equals and hashcode basd on sub process name and id 


    }

    public class Grade{

      // getters and setters
      private int gradeId;
      // getters and setters
      private String gradeName;

    }

现在遍历结果集并填充这些对象,创建一个进程检查列表,同时添加新进程,无论进程是否已存在......如果是,则重复检查子进程和等级仅在添加数据时才添加数据新。

答案 1 :(得分:1)

扩展answer by prashant

的伪代码:

String sql = "SELECT pId, pName, sId, sName, gId, gName" +
              " FROM ..." +
              " LEFT JOIN ..." +
             " WHERE ..." +
             " ORDER BY pId, sId, gId"; // <-- IMPORTANT !!!
rs = stmt.executeQuery(sql)

List<Process> processes = new ArrayList<>();
Process p = null;
SubProcess s = null;
while (rs.next()) {
    if (p == null || p.getId() != rs.getInt("pId")) {
        p = new Process(rs.getInt("pId"), rs.getString("pName"));
        processes.add(p);
        s = null; // force new SubProcess
    }
    if (rs.getInt("sId") == 0/*null*/)
        continue; // skip, no SubProcess found for Process
    if (s == null || s.getId() != rs.getInt("sId")) {
        s = new SubProcess(rs.getInt("sId"), rs.getString("sName"));
        p.addSubProcess(s);
    }
    if (rs.getInt("gId") == 0/*null*/)
        continue; // skip, no Grade found for SubProcess
    Grade g = new Grade(rs.getInt("gId"), rs.getString("gName"));
    s.addGrade(g);
}
// Now generate JSON from 'processes' list