三级分类
1. 数据结构解析
对于一级分类,它的parent_cid = 0; 二级分类的 parent_cid是对应一级分类的cat_id; 三级分类的parent_cid 是对应的二级分类的 cat_id
CategoryEntity 实体类
package com.wy.product.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* @author HelloWorld
* @create 2022/10/16 09:08
* @email helloworld.dng@gmail.com
*/
@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显示]
*/
private Integer showStatus;
/**
*排序
*/
private Integer sort;
/**
*图标地址
*/
private String icon;
/**
*计量单位
*/
private String productUnit;
/**
*商品数量
*/
private Integer productCount;
@TableField(exist = false)
private Set<CategoryEntity> children;
}
2. 代码实现
@Resource
private CategoryDao categoryDao;
/**
* @description 实现三级分类菜单
* 首先获取1级分类,然后递归获取所有子分类
* @author HelloWorld
* @create 2022/10/16 11:07
* @param
* @return java.util.Set<com.wy.product.entity.CategoryEntity>
*/
@Override
public Set<CategoryEntity> setWithTree() {
List<CategoryEntity> categoryList = new LambdaQueryChainWrapper<>(categoryDao).list();
return categoryList.stream()
.filter((categoryEntity) -> 0 == categoryEntity.getParentCid())
.map((root) -> {
root.setChildren(getChildren(root, categoryList));
return root;
})
.sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* @description 获取所有子分类
* @author HelloWorld
* @create 2022/10/16 11:05
* @param root
* @param all
* @return java.util.Set<com.wy.product.entity.CategoryEntity>
*/
public Set<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
return all.stream()
.filter((category) -> category.getParentCid().equals(root.getCatId()))
.map((category) -> {
category.setChildren(getChildren(category, all));
return category;
})
.sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
.collect(Collectors.toCollection(LinkedHashSet::new));
}