设计思路:最简单的查询全部分组数据,然后通过 Java 程序控制分层问题,借用临时 Map 来快速定位父子分组关系噢~
- SQL
DROPTABLEIFEXISTS`t_ac_api_group`; CREATETABLE`t_ac_api_group` ( `group_id`varchar(32) NOTNULLCOMMENT'分组Id', `group_name`varchar(30) NOTNULLCOMMENT'分组名称', `group_pid`varchar(32) NOTNULLCOMMENT'分组父Id', `group_type`tinyint(1) NOTNULLCOMMENT'分组类型', `group_del`tinyint(1) NOTNULL, `group_createtime`datetimeNOTNULL, `group_updatetime`datetimeNOTNULL, PRIMARYKEY (`group_id`) USINGBTREE) ENGINE=InnoDBDEFAULTCHARSET=utf8;
- 伪代码
importcom.baomidou.mybatisplus.annotation.*; importcom.fasterxml.jackson.annotation.JsonInclude; importlombok.AllArgsConstructor; importlombok.Builder; importlombok.Data; importlombok.NoArgsConstructor; importjava.time.LocalDateTime; importjava.util.List; /*** @author Lux Sun* @date 2020/6/5*/"t_ac_api_group") (publicclassApiGroupPO { type=IdType.ASSIGN_UUID) (privateStringgroupId; privateStringgroupName; privateStringgroupPid; privateIntegergroupType; exist=false) (privateList<ApiGroupPO>groupList; fill=FieldFill.INSERT, select=false) (privateIntegergroupDel; fill=FieldFill.INSERT) (privateLocalDateTimegroupCreatetime; fill=FieldFill.INSERT_UPDATE) (privateLocalDateTimegroupUpdatetime; }
/*** [OK]* 获取根分组集* @return*/publicList<ApiGroupPO>getGroupListByType() { QueryWrapper<ApiGroupPO>qw=newQueryWrapper<>(); qw.orderByDesc(Const.Group.COLUMN_GROUPUPDATETIME); List<ApiGroupPO>apiGroupPoList=groupDao.selectList(qw); apiGroupPoList=dealApiGroupLayer(apiGroupPoList); returnapiGroupPoList; } /*** [OK]* 处理分组层级* @param apiGroupList*/privateList<ApiGroupPO>dealApiGroupLayer(List<ApiGroupPO>apiGroupList) { Map<String, ApiGroupPO>id2GroupMap=apiGroupList.stream().collect(Collectors.toMap(ApiGroupPO::getGroupId, apiGroupPO->apiGroupPO)); List<ApiGroupPO>finalApiGroupPoList=Lists.newArrayList(); for (ApiGroupPOapiGroupPo : apiGroupList) { StringgroupPid=apiGroupPo.getGroupPid(); if (Const.Group.VAL_GROUPPIDROOT.equals(groupPid)) { finalApiGroupPoList.add(apiGroupPo); continue; } ApiGroupPOapiParentGroupPo=id2GroupMap.get(groupPid); // 如果为空, new List 赋值过去; 不为空也不影响, 大不了自己 set 自己一下apiParentGroupPo.setGroupList(Optional.ofNullable(apiParentGroupPo.getGroupList()).orElse(Lists.newArrayList())); apiParentGroupPo.getGroupList().add(apiGroupPo); } returnfinalApiGroupPoList; }