[英]convert a result set with flat column structure into hierarchical data structure
I have a result of a db query in java.sql.ResultSet
that needs to be converted to hierarchical data structure. 我在
java.sql.ResultSet
中有一个数据库查询的结果,该查询需要转换为分层数据结构。 It looks a bit like so: 看起来像这样:
name|version|pname|code|count
n1|1.1|p1|c1|3
n1|1.1|p1|c2|2
n1|1.1|p2|c1|1
n1|1.2|p1|c1|0
n2|1.0|p1|c1|5
I need that converted into a hierarchical data structure: 我需要将其转换为分层数据结构:
N1
+ 1.1
+ p1
+ c1(3)
+ c2(2)
+ p2
+ c1(1)
+ 1.2
+ p1
+ c1(0)
N2
+ 1.0
+ p1
+ c1(5)
So my data structure can look something like this 所以我的数据结构看起来像这样
Name {
String name
List<Version> versions
}
Version {
String version
List<PName> pnames
}
PName {
String pName
List<CodeCount> codeCounts
}
CodeCount {
String code
Integer count
}
Anyone have suggestions/code snippets on the best way to do this? 有人对最佳方法有建议/代码段吗?
There are a few ways, and how you do it depends on how robust your solution needs to be. 有几种方法,如何执行取决于解决方案的坚固性。
One would be to just write a couple of objects that had the attributes in the database. 一种方法是只编写几个在数据库中具有属性的对象。 Then you could get the result set, and iterate over it, creating a new object each time the key field (for example, "name") changed, and adding it to a list of that object.
然后,您可以获取结果集并对其进行迭代,每次键字段(例如,“名称”)更改时都创建一个新对象,并将其添加到该对象的列表中。 Then you'd set the attributes appropriately.
然后,您将适当地设置属性。 That is the "quick and dirty" solution.
那是“快速而肮脏的”解决方案。
A slightly more robust way would be to use something like Hibernate to do the mapping. 一种更健壮的方法是使用类似Hibernate的方法进行映射。
If you do decide to do that, I would also suggest redoing your tables so that they accurately reflect your object structure. 如果您决定这样做,我也建议您重做表,以便它们准确反映您的对象结构。 It may not be needed if you just want a fast solution.
如果您只想快速解决方案,则可能不需要。 But if you are seeking a robust solution for commercial or enterprise software, it's probably a good idea.
但是,如果您正在寻找针对商业或企业软件的可靠解决方案,则可能是个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.