服务三级菜单分类设计

一、三级分类查询-递归-树形结构数据获取

样例:

服务三级菜单分类设计_第1张图片

随着服务的功能增多,后期需要对这类数据进行维护(增删改查) 。 所以三级分类数据应该来源于数据库,而不是前端写死。

1、表设计

样例:

服务三级菜单分类设计_第2张图片

 数据以一定的规则存储在数据库,每一个子分类都有自己的id和父id

服务三级菜单分类设计_第3张图片

2、查询

1)、查出所有分类的子分类,以树形结构组装起来

第一步:先查出所有分类:ListAll()

List entities = baseMapper.selectList(null); //查询条件为null

第二步:组装成父子的树形结构:

①先查出所有一级分类

List entities = baseMapper.selectList(null); //查询条件为null

List level1 = entities.stream().filter((entiy)-> {
    entiy.getParentCid() == 0;  //.filter()过滤条件:当"父id == 0"时,说明是一级分类
}).collect(Collectors.tolist());
    
    return level1;

②查出所有子分类,首先在Entity里加入可以封装子分类的集合

  注意:@TableField(exist = false):不是数据库中的字段,只是用来封装子数据

//自定义属性
@JsonInclude(JsonInclude.Include.NON_EMPTY) //不为空的时候才返回给前端
@TableField(exist = false) //在数据库中不存在
private List children;
public .......{

   List entities = baseMapper.selectList(null); //查询条件为null

   List level1 = entities.stream().filter((entiy)-> { 
        entiy.getParentCid() == 0; //.filter()过滤条件:当"父id == 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 level1;
}


//递归查找所有菜单的子菜单方法
public List getChildrens(CategoryEntity root, List all) {
   List children = all.stream().filter(entity -> { 
   return entity.getParentCid() == root.getCatId());  //过滤,当子菜单的父id == root菜单的id
}).map(entity -> {
   //1、找到子菜单
   entity.setChildren(getChildrens(entity, all)) 
   return entity;
}).sorted((menu1,menu2)->{  
   //2、菜单的排序
   return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).collect(Collectors.toList());

   return children;
}

你可能感兴趣的:(数据库)