商品三级分类递归树形结构获取
controller
在product模块的控制层
GategoryController中新增方法
/**
* 返回三级分类tree
*/
@RequestMapping("/list/tree")
public R listTree(){
List<CategoryEntity> tree = categoryService.getTree();
return R.ok().put("data", tree);
}
entity
增加子类结构
@TableField(exist = false) mybatis-plus注解——不在表结构中
/**
* 子类category
*/
@TableField(exist = false)
private List<CategoryEntity> child;
service
GateService新增
List<CategoryEntity> getTree();
实现类
@Override
public List<CategoryEntity> getTree() {
//查询出所有
List<CategoryEntity> all =baseMapper.selectList(null);
//组装成父子结构——改变category的结构
//找到所有的一级分类
List<CategoryEntity> lv1Menu = all.stream().filter(menu->
menu.getParentCid()== 0
).map((menu)->{
//通过递归找到子分类
menu.setChild(getChild(menu,all));
return menu;
}).sorted((menu1,menu2)->{
return menu1.getSort()-menu2.getSort();
}).collect(Collectors.toList());
return lv1Menu;
}
其中map()中通过调用递归方法找到所有子类
private List<CategoryEntity> getChild(CategoryEntity root , List<CategoryEntity> all){
List<CategoryEntity> child = all.stream().filter(menu->
menu.getParentCid()==root.getCatId()).map((menu)->{
//通过递归找到子分类
menu.setChild(getChild(menu,all));
return menu;
}).sorted((menu1,menu2)->{
return menu1.getSort()-menu2.getSort();
}).collect(Collectors.toList());
return child;
}
测试
启动项目访问
http://localhost:10000/product/category/list/tree
得到json