使SQL实现树形查询
1 树形结构固定,即固定几层结构,可以采用数据库连接查询,这里以两张表为例:
select one.id, one.label, two.id, two.labelfrom course_category one inner join course_category two on two.parentid = one.idwhere one.parentid = '1' and one.is_show = '1' and two.is_show = '1'order by one.orderby, two.orderby
2 树形结构可能变化,采用数据库的递归进行查询
with recursive t1 as (select * from course_category where id = '1' union all select t2.* from course_category t2 inner join t1 on t2.parentid = t1.id)select *from t1order by t1.id, t1.orderby;
Java代码实现
递归查询数据库
public List
一次性全部查询出来,用Java代码实现数据的树形分解
public class TreeDemo{ public static void main(String[] args) { List treeList = init(); List collect = treeList.stream() .filter(item -> item.getPid() == 0)//构造最外层节点,即id=0的节点 .map(item -> { item.setChildrenList(getChildren(item, treeList));//id=0的节点就为他设置孩子节点 return item; }). collect(Collectors.toList()); System.out.println(new Gson().toJsonTree(collect)); } //获得孩子节点 private static List getChildren(TreeEntity treeEntity, List treeEntityList) { List collect = treeEntityList.stream() .filter(item -> item.getPid().equals(treeEntity.getId()))//判断当前节点的父id是不是要设置节点的id .map(item -> { item.setChildrenList(getChildren(item, treeEntityList));//如果是 为其设置孩子节点 通过递归 为每个除了最外层节点的节点设置孩子节点 return item; }) .collect(Collectors.toList()); return collect; } }
注:以上Java代码粘贴自网络
来源地址:https://blog.csdn.net/weixin_46757028/article/details/130415038