三级分类示意图
一、分类数据导入数据库
主要用到 pms_category 这张表,我们先查看其表结构
将数据导入此表
二、编写查出所有分类及子分类的方法
首先在 CategoryController 中编写处理请求的方法
/**
* 查出所有分类以及子分类,以树形结构组装起来
*/
@RequestMapping("/list/tree")
public R list(){
List<CategoryEntity> entities = categoryService.listWithTree();
return R.ok().put("data", entities);
}
对应的 CategoryServiceImpl 中
@Override
public List<CategoryEntity> listWithTree() {
// 1. 查出所有类
List<CategoryEntity> entities = baseMapper.selectList(null);
// 2. 组装成父子的树形结构
List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map((menu)->{
menu.setChildren(getChildrens(menu, entities));
return menu;
}).sorted((menu1, menu2)->{
// 会报空指针异常, 在此要进行处理
return (menu1.getSort() == null? 0:menu1.getSort()) - (menu2.getSort() == null? 0: menu2.getSort());
}).collect(Collectors.toList());
return level1Menus;
}
// 递归查找所有菜单的子菜单
private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity->{
// 1、找到子菜单
categoryEntity.setChildren(getChildrens(categoryEntity, all));
return categoryEntity;
}).sorted((menu1, menu2)->{
// 2、菜单的排序
// 会报空指针异常, 在此要进行处理
return (menu1.getSort() == null? 0:menu1.getSort()) - (menu2.getSort() == null? 0: menu2.getSort());
}).collect(Collectors.toList());
return children;
}
这里主要用到了 Java8 新特性,看不懂的可以查阅相关文档
注意:我们要保存每一类对应的子类,可以在 CategoryEntity 中新增一个属性 children 进行存放
@TableField(exist = false)
private List<CategoryEntity> children;
这里 @TableField
注解用来标识此属性不在数据库表中存在,防止 MyBatisPlus 集成的 mapper 误识
三、测试
启动服务
这里有 SpringCloud Alibaba Nacos 报错,可以不用管
在浏览器中输入 http://localhost:10000/product/category/list/tree 测试
确实分类分级了