实体类

  1. @Data
  2. @TableName("pms_category")
  3. public class CategoryEntity implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. /**
  6. * 分类id
  7. */
  8. @TableId
  9. private Long catId;
  10. /**
  11. * 分类名称
  12. */
  13. private String name;
  14. /**
  15. * 父分类id
  16. */
  17. private Long parentCid;
  18. /**
  19. * 层级
  20. */
  21. private Integer catLevel;
  22. /**
  23. * 是否显示[0-不显示,1显示]
  24. */
  25. @TableLogic(value = "1", delval = "0")
  26. private Integer showStatus;
  27. /**
  28. * 排序
  29. */
  30. private Integer sort;
  31. /**
  32. * 图标地址
  33. */
  34. private String icon;
  35. /**
  36. * 计量单位
  37. */
  38. private String productUnit;
  39. /**
  40. * 商品数量
  41. */
  42. private Integer productCount;
  43. @JsonInclude(JsonInclude.Include.NON_EMPTY)
  44. @TableField(exist = false)
  45. private List<CategoryEntity> children;
  46. }

实现

  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. }