谷粒商城38 - 后端-商品服务-API-三级分类-递归树形结构查询

需求

显示如下图所示的三级分类

导入数据

在gulimall_pms 库中, 导入商品分类的数据

导入pms_category 表数据, 该表, 主要是有分类id 和父级id , 形成了父子结构

导入的sql , 可以在码云中下载

https://gitee.com/code_life_git/gulimall/tree/master/sql


导入后 , 如下 :

代码实现

model修改

在CategoryEntity 中, 增加如下的成员变量, 用于存储子分类

    /**
     * 子分类, 用于拼接查询树形结果
     */
	@TableField(exist = false)
	private List<CategoryEntity> children;

Controller

编写如下的接口

    /**
     *  查出所有分类以及子分类,  以树形结构组装起来
     */
    @RequestMapping("/list/tree")
    public R list(){
       List<CategoryEntity> entityList  = categoryService.listWithTree();

        return R.ok().put("data", entityList);
    }

Service

Service 编写如下的方法, 用于遍历查询出所有 和父节点和 递归查询出所有的子节点.
其中private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) 方法为核心. 用于递归查询父分类的子分类, 以及子分类的子分类

 /**
     * 方法名: listWithTree
     * 方法描述: 查询出所有的分类, 并拼装成父子结构
     * 修改日期: 2020/8/3 19:42
     * @param
     * @return java.util.List<com.atguigu.gulimall.product.entity.CategoryEntity>
     * @author https://javaweixin6.blog.csdn.net/
     * @throws
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出分类表所有数据
        List<CategoryEntity> entityList = baseMapper.selectList(null);

        //查询出所有的一级分类数据.  使用stream的api
        List<CategoryEntity> firstEntityList = entityList.stream().
                filter(categoryEntity -> categoryEntity.getParentCid() == 0).map((menu) -> {
                    //传递当前的商品分类, 和所有的分类,递归查询出子分类
                    menu.setChildren( getChildrens(menu,entityList));
                    return menu;
        } ).sorted((menu1,menu2)->{
            //进行排序
            return (menu1.getSort() ==null?0:menu1.getSort())- (menu2.getSort()==null?0 : menu2.getSort());
        }).collect(Collectors.toList());
        return firstEntityList;
    }

    /**
     * 递归查询子父类
     * @param root   当前节点的父id
     * @param all    所有的商品分类
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrenList = all.stream().filter(categoryEntity -> {
            //如果
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //子菜单可能还有子菜单, 因此递归查询 ,   查询出子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //进行排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return childrenList;
    }

测试

在数据库中,修改排序字段, 测试排序

浏览器中访问接口
http://localhost:9898/product/category/list/tree

返回数据如下, 成功进行了树形结构的拼装, 并且进行了排序, sort字段小的, 排在前面.

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/107771462