【发布时间】:2016-03-14 22:11:36
【问题描述】:
我的数据库中有一个这样的表:
等等……
如您所见,有多个根父级(没有 parent_id 的父级),每个类别都有 n 个子级。
我想使用这个类将其转换为 Java 中的树结构:
private int id;
private String name;
private int parent;
private List<Category> children;
我通过这个查询获得数据,我认为它可以改进:
SELECT c.*, ca.name, NVL(ca.parent_id, -1) AS parent_id FROM
(
SELECT id, name, parent_id FROM categories
) ca,
(
SELECT LISTAGG(id || ':' || name || ':' || DECODE(parent_id, NULL,
DECODE(id, NULL, NULL, -1), parent_id), ';')
WITHIN GROUP (ORDER BY id) AS children, parent_id AS id
FROM categories
GROUP BY parent_id HAVING parent_id IS NOT NULL
) c
WHERE c.id = ca.id
我得到每个类别(id、name 和 parent_id)和一个字符串及其子项。
然后我循环抛出每个 ResultSet
List<Category> categories = new ArrayList<Category>();
while (rs.next()) {
Category c = new Category();
c = JdbcToModel.convertToCategory(rs); //
if (c.getParent() == -1) { // parent_id is null in database
categories.add(c);
else {
categories = JdbcToModel.addCategoryToTree(categories, c);
}
}
方法convertToCategory:
public static Category convertToCategory(ResultSet rs) {
Category toRet = new Category();
List<Category> children = new ArrayList<Category>();
try {
children = parseCategoriesFromReview(rs.getString("children"));
toRet.setId(rs.getInt("id"));
toRet.setName(rs.getString("name"));
toRet.setParent(rs.getInt("parent_id"));
toRet.setChildren(children);
} catch (Exception e) {
e.printStackTrace();
}
return toRet;
}
解析childs字符串时的方法parseCategoriesFromReview:
public static List<Category> parseCategoriesFromReview(String categoriesString) {
List<Category> toRet = new ArrayList<Category>();
try {
if (!categoriesString.equals("::")) {
String [] categs = categoriesString.split(";");
for (String categ : categs) {
String [] category = categ.split(":");
Category c = new Category(Integer.parseInt(category[0]), category[1], Integer.parseInt(category[2]), new ArrayList<Category>());
toRet.add(c);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return toRet;
}
以及递归方法addCategoryToTree:
public static List<Category> addCategoryToTree(List<Category> categories, Category c) {
try {
for (Category ct : categories) {
if (ct.getId() == c.getParent()) {
ct.getChildren().add(c);
break;
} else {
return addCategoryToTree(ct.getChildren(), c);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return categories;
}
我认为这个方法最大的问题是......我从来没有写过一个内部有循环的递归方法,我不知道它是否正确。关键是我得到了一个树结构,但只有几个类别。最终的树没有这么多。
也许我让事情变得复杂,但我不知道如何以另一种方式做到这一点..
有人帮忙吗??
问候!
【问题讨论】:
标签: java oracle recursion tree