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

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

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我才是真的封不觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值