1.导入分类数据
把资料附带的sql执行下
2.Controller层代码
CategoryController类内添加如下代码
/**
* 获取树形菜单
*/
@RequestMapping("/list/tree")
public R listWithTree(){
List<CategoryEntity> categoryEntityList = categoryService.listWithTree();
return R.ok().put("page", categoryEntityList);
}
2.entity层代码
CategoryEntity类内添加如下代码 因为在表中不存在该属性,所以加如下注解,用来存子分类
@TableField(exist = false)
private List<CategoryEntity> children;
3.service层代码
CategoryService类内添加如下代码
List<CategoryEntity> listWithTree();
CategoryServiceImpl类内添加如下代码
大致的操作就是先获取1级分类获取子分类并递归设置进去
@Override
public List<CategoryEntity> listWithTree() {
List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
//获取所有父级菜单
List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity ->
categoryEntity.getParentCid() == 0
).map((menu) -> {
menu.setChildren(getChildren(menu, categoryEntityList));
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> getChildren(CategoryEntity menu, List<CategoryEntity> categoryEntityList) {
List<CategoryEntity> collect = categoryEntityList.stream().filter(categoryEntity ->
categoryEntity.getParentCid() == menu.getCatId()
).map((child) -> {
child.setChildren(getChildren(child, categoryEntityList));
return child;
}).sorted((child1, child2) -> {
return (child1.getSort()==null?0:child1.getSort()) - (child2.getSort()==null?0:child2.getSort());
}).collect(Collectors.toList());
return collect;
}
关于jdk1.8 stream可以看看
https://blog.youkuaiyun.com/leehsiao/article/details/91354163

被折叠的 条评论
为什么被折叠?



