菜单/部门树形结构,查询子节点查出完整的树形结构
/*
* 1、查询包含关键字的节点
* 2、遍历节点
* 1)查询该节点的所有父节点,添加集合中
* 2)查询该节点的所有子节点,添加集合中
* 3、去重
* 4、将当前节点结合生成树结构
*
*/
1、自己根据实际情况写查询
2、查询该节点的所有父节点,添加集合中
<!-- 查询父节点信息 -->
<select id="queryParentDeparts" resultType="com.modules.system.model.SysDepartNbTreeModel">
SELECT distinct t.* FROM SYS_DEPART t
where t.del_flag = '0'
START WITH id in
<foreach collection="departIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
CONNECT BY PRIOR PARENT_ID = ID
ORDER BY depart_order asc;
</select>
<!-- 查询子节点信息 -->
<select id="queryChildDeparts" resultType="com.casic.modules.system.model.SysDepartNbTreeModel">
SELECT distinct t.* FROM SYS_DEPART t
where t.del_flag = '0'
START WITH id in
<foreach collection="departIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
CONNECT BY PRIOR ID = PARENT_ID
ORDER BY depart_order asc;
</select>
3、去重
用流或者set或者其他方法
我用流处理
tempList = tempList.stream().distinct().collect(Collectors.toList());
4、生成树结构(直接贴源码)
public List<SysDepartTreeModel> queryByCondition(String keyWord) {
/*
* 1、查询包含关键字的节点
* 2、遍历节点
* 1)查询该节点的所有父节点,添加集合中
* 2)查询该节点的所有子节点,添加集合中
* 3、去重
* 4、将当前节点结合生成树结构
*
*/
List<SysDepartTreeModel> result = new ArrayList<>();
List<SysDepartTreeModel> tempList = new ArrayList<>();
// 1、查询包含关键字的节点
List<SysDepart> targetDeparts = this.list(new QueryWrapper<SysDepart>().like("DEPART_NAME", keyWord));
List<String> departIds = targetDeparts.stream().map(SysDepart::getId).collect(Collectors.toList());
// 1)查询该节点的所有父节点,添加集合中
List<SysDepartTreeModel> parentDeparts = sysDepartMapper.queryParentDeparts(departIds);
// 2)查询该节点的所有子节点,添加集合中
List<SysDepartTreeModel> childDeparts = sysDepartMapper.queryChildDeparts(departIds);
tempList.addAll(parentDeparts);
tempList.addAll(childDeparts);
// 去重
tempList = tempList.stream().distinct().collect(Collectors.toList());
if(!CollectionUtils.isEmpty(tempList)){
for(SysDepartTreeModel sysDepart:tempList){
// 我这种是没有根节点,具体根据实际情况修改,有的是0,有的是1
if (sysDepart.getParentId() == null){
result.add(sysDepart);
}
for(SysDepartTreeModel depart:tempList){
if(depart.getParentId()==null){
continue;
}
if(depart.getParentId().equals(sysDepart.getId())){
sysDepart.getChildren().add(depart);
}
}
}
}
return result;
}
// 欢迎私信交流