根据子节点递归查询所有父节点
程序员文章站
2022-05-30 16:42:06
...
有个需求,需要根据给定的子节点向上递归查询所有父节点,网上查找了一些,但是都不是很满意,有的是需要用到全局变量定义存储列表,但是会有并发问题,然后自己手写一个
@Test
void contextLoads1() {
List<School> list = new ArrayList<School>();
list.add(new School(1,"张三丰",0));
list.add(new School(2,"张无忌",1));
list.add(new School(3,"张翠山",2));
list.add(new School(4,"殷梨亭",3));
list.add(new School(5,"俞莲舟",3));
list.add(new School(6,"宋远桥",4));
list.add(new School(7,"宋远桥",5));
List<Integer> idList = new ArrayList<>();
//以id为6的对象为例,他的父节点是4,先将本身的id设置进列表中
idList.add(6);
List<Integer> integerList = getpid(idList, 4, list);
System.out.println(integerList);
}
public List<Integer> getpid(List<Integer> idList,Integer pid,List<School> schools){
School school = schools.stream().filter(s -> s.getId() == pid).findFirst().get();
idList.add(school.getId());
if (school.getId() != 1){
getpid(idList,school.getPid(),schools);
}
return idList;
}
结果为:
[6, 4, 3, 2, 1]
符合期望
,还有一种方法就是直接在数据库中写一个递归的函数,这也是可行的,
BEGIN
DECLARE idStr VARCHAR(2048);
DECLARE childIdStr VARCHAR(2048);
SET idStr = '$';
SET childIdStr = CAST(orgId AS CHAR);
WHILE childIdStr IS NOT NULL DO
SET idStr = CONCAT(idStr, ',', childIdStr);
SELECT GROUP_CONCAT(pid) INTO childIdStr FROM school WHERE FIND_IN_SET(id, childIdStr) > 0;
END WHILE;
RETURN idStr;
END
函数名以及传入和返回参数:
fc_queryParentDeviceTypeId
返回的是这样的结果
$,6,4,3,2,1
后续可以自己处理