1. package com.zsy.gulimall.product.entity;
  2. import com.baomidou.mybatisplus.annotation.*;
  3. import java.io.Serializable;
  4. import java.util.List;
  5. import com.fasterxml.jackson.annotation.JsonInclude;
  6. import io.swagger.annotations.ApiModel;
  7. import io.swagger.annotations.ApiModelProperty;
  8. import lombok.Data;
  9. import lombok.EqualsAndHashCode;
  10. /**
  11. * <p>
  12. * 商品三级分类
  13. * </p>
  14. *
  15. * @author liulq
  16. * @since 2022-03-19
  17. */
  18. @Data
  19. @TableName("pms_category")
  20. @EqualsAndHashCode(callSuper = false)
  21. @ApiModel(value="PmsCategory对象", description="商品三级分类")
  22. public class PmsCategory implements Serializable {
  23. private static final long serialVersionUID = 1L;
  24. @ApiModelProperty(value = "分类id")
  25. @TableId(value = "cat_id", type = IdType.AUTO)
  26. private Long catId;
  27. @ApiModelProperty(value = "分类名称")
  28. private String name;
  29. @ApiModelProperty(value = "父分类id")
  30. private Long parentCid;
  31. @ApiModelProperty(value = "层级")
  32. private Integer catLevel;
  33. @ApiModelProperty(value = "是否显示[0-不显示,1显示]")
  34. @TableLogic(value = "1", delval = "0")
  35. private Integer showStatus;
  36. @ApiModelProperty(value = "排序")
  37. private Integer sort;
  38. @ApiModelProperty(value = "图标地址")
  39. private String icon;
  40. @ApiModelProperty(value = "计量单位")
  41. private String productUnit;
  42. @ApiModelProperty(value = "商品数量")
  43. private Integer productCount;
  44. @JsonInclude(JsonInclude.Include.NON_EMPTY)
  45. @TableField(exist = false)
  46. private List<PmsCategory> children;
  47. }

实现

  1. public List<CategoryEntity> listWithTree() {
  2. //1、查出所有分类
  3. List<CategoryEntity> entities = baseMapper.selectList(null);
  4. //2、组装成父子的树形结构
  5. //2.1)、找到所有的一级分类,给children设置子分类
  6. return entities.stream()
  7. // 过滤找出一级分类
  8. .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
  9. // 处理,给一级菜单递归设置子菜单
  10. .peek(menu -> menu.setChildren(getChildless(menu, entities)))
  11. // 按sort属性排序
  12. .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
  13. .collect(Collectors.toList());
  14. }
  15. /**
  16. * 递归查找所有菜单的子菜单
  17. */
  18. private List<CategoryEntity> getChildless(CategoryEntity root, List<CategoryEntity> all) {
  19. return all.stream()
  20. .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
  21. .peek(categoryEntity -> {
  22. // 找到子菜单
  23. categoryEntity.setChildren(getChildless(categoryEntity, all));
  24. })
  25. .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
  26. .collect(Collectors.toList());
  27. }

效果

image.png