List queryResult = deptRepository.getBaseMapper().query(dto) ;

2、递归,把目标数据到根节点的所有节点找出来,并存起来

* 模糊匹配查询 * @param queryResult 模糊查询的部门结果集 * @param all 所有部门 * @return public static List < Tree < String >> getDeptTree ( List<Dept> queryResult, List<Dept> all ){ //ID分组 Map < String , Dept > base = queryResult. stream () . collect ( Collectors . toMap ( SysDept ::getId, ele -> ele, (v1, v2) -> v2)); Map < String , Dept > origin = all. stream () . collect ( Collectors . toMap ( SysDept ::getId, ele -> ele, (v1, v2) -> v2)); //存放最终结果 Map < String , Dept > result = new HashMap <>(queryResult. size ()); //遍历结果集 for ( Map . Entry < String , Dept > entry : base. entrySet ()){ result. put (entry. getKey (),entry. getValue ()); //递归找出全链路节点 getAllParentId (result, entry. getValue (). getParentId (), origin); return getDeptTree ( SysConstant . ROOT_ID , new LinkedList <>(result. values ())); * 递归找出全链路节点 * @param result 存放结果容器 * @param parentId 父ID * @param origin 所有部门map private static void getAllParentId ( Map < String , Dept> result, String parentId, Map < String , Dept> origin ){ //存在则跳过 if (result. containsKey (parentId)){ return ; //递归获取 Dept dept = origin. get (parentId); if ( null != dept){ result. put (parentId,dept); //Constant.ROOT_ID 为根节点ID if (!dept. getParentId (). equals ( Constant . ROOT_ID )){ getAllParentId (result, dept. getParentId (), origin);

3、把第二步的结果转成树输出

* 集合转树,这里用的是hutool的 treeUtil * @param rootId 根节点ID * @param list 目标集合 * @return public static List < Tree < String >> getDeptTree ( String rootId,List<Dept> list ){ //树配置 TreeNodeConfig nodeConfig = new TreeNodeConfig (); nodeConfig. setIdKey ( "id" ); nodeConfig. setParentIdKey ( "parentId" ); nodeConfig. setNameKey ( "name" ); nodeConfig. setWeightKey ( "orderNum" ); List < Tree < String >> result; //生成树 result = TreeUtil . build (list, rootId, nodeConfig, ( object , tree) -> { tree. setId ( object . getId ()); tree. setParentId ( object . getParentId ()); tree. setName ( object . getName ()); tree. setWeight ( object . getOrderNum ()); tree. putExtra ( "type" , object . getType ()); tree. putExtra ( "status" , object . getStatus ()); return result;
粉丝