新闻详情

新闻详情

首页 / 资讯中心 / 详情

P45 创建三级类目树形数据结构

发布时间:2026/7/3 2:51:42
P45 创建三级类目树形数据结构
1.三级类目实体类创建catagory表的表结构首先一级类目的parent_cid为0二级类目以及三级类目的parent_cid为上一级的cat_idsort字段用于排序.与catagory表对应的实体类package com.atguigu.gulimail.product.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; /** * 商品三级分类 * * author bryan * email bryanliugulimall.com * date 2022-09-24 17:49:33 */ Data TableName(pms_category) public class CategoryEntity implements Serializable { private static final long serialVersionUID 1L; /** * 分类id */ TableId private Long catId; /** * 分类名称 */ private String name; /** * 父分类id */ private Long parentCid; /** * 层级 */ private Integer catLevel; /** * 是否显示[0-不显示1显示] */ TableLogic(value 1, delval 0) private Integer showStatus; /** * 排序 */ private Integer sort; /** * 图标地址 */ private String icon; /** * 计量单位 */ private String productUnit; /** * 商品数量 */ private Integer productCount; JsonInclude(JsonInclude.Include.NON_EMPTY) TableField(exist false) private ListCategoryEntity children; }注意我们要保存每一类对应的子类可以在 CategoryEntity 中新增一个属性 children 进行存放。这里TableField注解用来标识此属性不在数据库表中存在防止 MyBatisPlus 集成的 mapper 误识。2.三级类目查询后台代码实现首先在 CategoryController 中编写处理请求的方法/** * 查出所有分类以及子分类以树形结构组装起来 */ RequestMapping(/list/tree) public R list(){ ListCategoryEntity entities categoryService.listWithTree(); return R.ok().put(data, entities); }categoryService中的listWithTree具体实现Override public ListCategoryEntity listWithTree() { // 1. 查出所有类 ListCategoryEntity entities baseMapper.selectList(null); // 2. 组装成父子的树形结构 ListCategoryEntity level1Menus entities.stream().filter((categoryEntity) - { return categoryEntity.getParentCid() 0; }).map((menu)-{ menu.setChildren(getChildrens(menu, entities)); return menu; }).sorted((menu1, menu2)-{ // 会报空指针异常, 在此要进行处理 return (menu1.getSort() null? 0:menu1.getSort()) - (menu2.getSort() null? 0: menu2.getSort()); }).collect(Collectors.toList()); return level1Menus; } // 递归查找所有菜单的子菜单 private ListCategoryEntity getChildrens(CategoryEntity root, ListCategoryEntity all) { ListCategoryEntity children all.stream().filter(categoryEntity - { return categoryEntity.getParentCid() root.getCatId(); }).map(categoryEntity-{ // 1、找到子菜单 categoryEntity.setChildren(getChildrens(categoryEntity, all)); return categoryEntity; }).sorted((menu1, menu2)-{ // 2、菜单的排序 // 会报空指针异常, 在此要进行处理 return (menu1.getSort() null? 0:menu1.getSort()) - (menu2.getSort() null? 0: menu2.getSort()); }).collect(Collectors.toList()); return children; }
网站建设 高端定制 企业官网