java 数据查询组装树状图结构-数据库查询

时间:2025-03-20 09:11:41

查询数据库组装成树状结构数据(学习笔记)

数据库
careate table category{
id int PRIMARY KEY COMMENT '主键',
level int COMMENT '等级',
category_name varchar(7) COMMENT '类目名',
parent_id int COMMENT '父节点id',
parent_name varchar(7) COMMENT '父节点名'
}
Sql语句
sql 语句
select id,name,level from category where level=? or parent_id=?

//select * from category where parent_id=?

实体类(bean层)

//bean
public class Category{
 private int id;
 private String categoryName;
 private int  parentId;
 private String parentName;
 private int level;
 private List<Category> nodes=new ArrayList<>();
 //get ,set方法省略
}

mapper

interface CategoryMapper{

//调用sql select id,name,level from category where level=? or parent_id=?
//查询id,name,level
List<Category> findAll(Category category);

}

service层

public List<Category> treeSelect(Category category){
@Resource
private CategoryMapper categoryMapper;
//调用
 List<Category> categoryList=(categoryNew);
// List<Category> mapList = new ArrayList<>();
 Category categoryLists=null;
 
 for(int i=0;i<();i++){
 Category categoryTemporary=new Category();
 //Category categoryLists=null;
 ();
 List<Category> list=treeSelect(categoryTemporary);
 categoryLists=(i);
 (list);
 //(categoryLists);
 }
 
//retrun mapList;
retrun categoryLists;
}
public static List<Category> findAll(){
Category categoryNew=new Category();
(1);//最顶端的
List<Category> list=treeSelect(category);
retrun list;
}

测试 模拟控制层

//测试
public static void main (String args[]){
List<Category> list=findAll();
}