1、这里以mongo表为例
//1、查询根节点ID
List<T> list = mongoTemplate.find(Query.query(Criteria.where("parentId").is("")), T.class);
List<String> rootIds = list.stream().map(x -> x.getId()).collect(Collectors.toList());
//2、根据根节点ID查询出所有底层节点ID,塞到result集合
List<String> result = new ArrayList<>();
for (String rootId : rootIds) {
List<String> treeBottomIds = getBottomIds(rootId, mongoTemplate);
result.addAll(treeBottomIds);
}
//3、根据底层节点ID,打印出完成层级路径
for(String string : result){
String treeNames = getTreeNames(string, "");
System.out.println(treeNames);
}
// 定义递归方法,获取指定节点的子孙节点中最底层节点的ID列表
private List<String> getBottomIds(String id, MongoTemplate mongoTemplate) {
// 查询当前节点的子节点
Query query = Query.query(Criteria.where("parentId").is(id));
List<KgDictType> childrenDocs = mongoTemplate.find(query, KgDictType.class);
// 如果当前节点没有子节点,则当前节点即为最底层节点,返回当前节点ID
if (childrenDocs.isEmpty()) {
return Collections.singletonList(id);
}
// 如果有子节点,则递归查询所有子孙节点的最底层节点ID,并将结果合并去重
Set<String> bottomIds = new HashSet<>();
for (KgDictType childDoc : childrenDocs) {
List<String> childBottomIds = getBottomIds(childDoc.getId(), mongoTemplate);
bottomIds.addAll(childBottomIds);
}
return new ArrayList<>(bottomIds);
}
public String getTreeNames(String id, String name) {
// 查询该节点信息
T node = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(id)), T.class);
// 如果未找到该节点,返回空字符串
if (node == null) {
return "";
}
// 查找上级树name
List<String> parentNames = new ArrayList<>();
String parentId = node.getParentId();
while (parentId != null) {
T parentNode = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(parentId)), T.class);
if (parentNode != null) {
parentNames.add(parentNode.getName());
parentId = parentNode.getParentId();
} else {
parentId = null;
}
}
// 查找下级树name
List<String> childNames = new ArrayList<>();
// List<T> children = mongoTemplate.find(Query.query(Criteria.where("parentId").is(node.getId())), T.class);
// for (T child : children) {
// childNames.add(child.getName());
// }
// 拼接结果并返回
Collections.reverse(parentNames); // 反转顺序,使其自上向下排列
parentNames.add(org.apache.commons.lang3.StringUtils.isEmpty(name)?node.getName():name);
parentNames.addAll(childNames);
return String.join("-", parentNames);
}
标签:String,树结构,List,mongoTemplate,parentId,query,节点,最底层 From: https://www.cnblogs.com/wj123bk/p/17415097.html