with recursive t1 as (
select * from course_category where id=#{id}
union all
select t2.* from course_category t2 inner join t1 on t1.id = t2.parentid
)
select * from t1
order by t1.id
public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
//调用mapper递归查询出分类信息
List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
//找到每个节点的子节点,最终封装成List<CourseCategoryTreeDto>
//先将list转成map,key就是结点的id,value就是CourseCategoryTreeDto对象,目的就是为了方便从map获取结点,filter(item->!id.equals(item.getId()))把根结点排除
Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
//定义一个list作为最终返回的list
List<CourseCategoryTreeDto> courseCategoryList = new ArrayList<>();
//从头遍历 List<CourseCategoryTreeDto> ,一边遍历一边找子节点放在父节点的childrenTreeNodes
courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
if (item.getParentid().equals(id)) {
courseCategoryList.add(item);
}
//找到节点的父节点
CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());
if (courseCategoryParent != null) {
if (courseCategoryParent.getChildrenTreeNodes() == null) {
//如果该父节点的ChildrenTreeNodes属性为空要new一个集合,因为要向该集合中放它的子节点
courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
}
//到每个节点的子节点放在父节点的childrenTreeNodes属性中
courseCategoryParent.getChildrenTreeNodes().add(item);
}
});
return courseCategoryList;
}
数据库递归,树形封装数据
于 2024-04-09 17:05:04 首次发布