1.三级类目实体类创建
catagory表的表结构,首先一级类目的parent_cid为0,二级类目以及三级类目的parent_cid为上一级的cat_id,sort字段用于排序.
与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 bryanliu@gulimall.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 List<CategoryEntity> children; }注意:我们要保存每一类对应的子类,可以在 CategoryEntity 中新增一个属性 children 进行存放。
这里@TableField注解用来标识此属性不在数据库表中存在,防止 MyBatisPlus 集成的 mapper 误识。
2.三级类目查询后台代码实现
首先在 CategoryController 中编写处理请求的方法
/** * 查出所有分类以及子分类,以树形结构组装起来 */ @RequestMapping("/list/tree") public R list(){ List<CategoryEntity> entities = categoryService.listWithTree(); return R.ok().put("data", entities); }categoryService中的listWithTree具体实现
@Override public List<CategoryEntity> listWithTree() { // 1. 查出所有类 List<CategoryEntity> entities = baseMapper.selectList(null); // 2. 组装成父子的树形结构 List<CategoryEntity> 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 List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) { List<CategoryEntity> 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; }