文章目录
前言
在日常的需求中 会有很多情况会去查询树形结构的情况,通常会采用递归查询。本文从另外一个思路,不使用递归查询。使用Map来组装 树形结构(仅适用于一个上级部门或组织的情况,多个上级的情况不适用)
一、具体思路
我们先将所有的组织或者部门查询出来:
<select id="queryRoleList" resultType="com.tqls.ucenter.console.user.entity.RoleModel">
select * from os_role
where 1=1
<if test="tp!=null and tp!=''">
and tp = #{tp}
</if>
<if test="appCode!=null and appCode!=''">
and app_code = #{appCode}
</if>
<if test="source!=null and source!=''">
and source = #{source}
</if>
</select>
将根节点先放入集合中,再组装后面部分
使用Map组装树形结构
public ResponseBean<List<DeptModel>> queryAllDept(String source) {
List<RoleModel> roles = roleService.queryRoleList(null, RoleTypeEnum.DEPT, source);
List<DeptModel> deptModels = BeanConvers.converList(roles, BeanConvers.role2DeptConver);
String uid = SubjectUtil.getUserId();
String parentId = "-1";
List<DeptModel> finalTreeList = new ArrayList<>();
DeptModel root = deptModels.stream().filter(item -> StringUtils.equals(parentId, item.getPrnId())).findFirst().get();
finalTreeList.add(root);
buildTreeByMap(deptModels, root, uid);
return new ResponseBean<>(finalTreeList);
}
public static void buildTreeByMap(List<DeptModel> deptModels, DeptModel parent, String uid) {
if (deptModels == null || deptModels.size() == 0) {
return;
}
if (parent != null
&& StringUtils.isNotEmpty(parent.getLeader())
&& parent.getLeader().contains(uid)
&& RoleStatusEnum.NORMAL.getCode().equals(parent.getSt())) {
parent.setEditEnable(true);
}
Map<String, DeptModel> nodeMap = new HashMap<>();
// 创建节点映射
for (DeptModel deptModel : deptModels) {
nodeMap.put(deptModel.getId(), deptModel);
}
nodeMap.put(parent.getId(),parent);
// 构建树形结构
for (DeptModel deptModel : deptModels) {
String parentId = deptModel.getPrnId();
if (!parentId.equals("-1")) {
DeptModel parentDept = nodeMap.get(parentId);
List<DeptModel> childenlist=parentDept.getChildren();
if (childenlist == null) {
childenlist = new ArrayList<>();
}
if(parent.isEditEnable() && RoleStatusEnum.NORMAL.getCode().equals(deptModel.getSt())){
deptModel.setEditEnable(parent.isEditEnable());
}
childenlist.add(deptModel);
parentDept.setChildren(childenlist);
}
}
}
上述内容有我们自己的业务逻辑代码。使用时请自行修改。代码本身逻辑并不复杂。有问题可以评论交流。
通过这个方法,可以将几十秒的查询优化到一秒以内。能极大的节约查询时间
总结
这是我自己优化组织树查询时的心得。有兴趣的可以评论交流