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

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

数据库
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 nodes=new ArrayList<>();
 //get ,set方法省略
}

mapper

interface CategoryMapper{

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

}

service层

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

测试 模拟控制层

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

你可能感兴趣的:(java学习笔记)