谷粒商城day31 -商品服务-API-三级分类-查询-递归树形结构数据获取

1.导入分类数据

把资料附带的sql执行下

2.Controller层代码

CategoryController类内添加如下代码
 /**
     * 获取树形菜单
     */
    @RequestMapping("/list/tree")
    public  R listWithTree(){
        List  categoryEntityList =  categoryService.listWithTree();
        return R.ok().put("page", categoryEntityList);
    }

2.entity层代码

CategoryEntity类内添加如下代码  因为在表中不存在该属性,所以加如下注解,用来存子分类
@TableField(exist = false)
	private List children;

3.service层代码

CategoryService类内添加如下代码
List listWithTree();
CategoryServiceImpl类内添加如下代码

大致的操作就是先获取1级分类获取子分类并递归设置进去

    @Override
    public List listWithTree() {
        List categoryEntityList = baseMapper.selectList(null);
        //获取所有父级菜单

        List 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 getChildren(CategoryEntity menu, List categoryEntityList) {

        List 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.csdn.net/leehsiao/article/details/91354163

你可能感兴趣的:(谷粒商城,级分类-查询-,递归树形结构数据获取)