欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

Java中使用递归算法实现子级架构的查询

发布时间:2025/3/19 java 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Java中使用递归算法实现子级架构的查询 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

场景

在实现企业架构管理时采用树形结构。如图:

现在要根据传递的id属性查询其有多少个子级架构。

注:如果A的id是B的pid,那么A就是B的父级。

实现

递归函数如下:

public void selectChild(List<Long> ids){//用来存取调用自身递归时的参数List<Long> temp= new ArrayList<Long>();//查询数据库中对应id的实体类List<SysEnterpriseOrg> sysEnterpriseOrgList = new ArrayList<SysEnterpriseOrg>();//遍历传递过来的参数idsfor (Long id :ids) {//查询子级架构//此处使用mybaatisPlus的条件构造器,查询pid等于id的对象QueryWrapper<SysEnterpriseOrg> sysEnterpriseOrgChildQueryWrapper = new QueryWrapper<SysEnterpriseOrg>();sysEnterpriseOrgChildQueryWrapper.eq("pid",id.toString());//查询结果返会一个listsysEnterpriseOrgList= sysEnterpriseOrgMapper.selectList(sysEnterpriseOrgChildQueryWrapper);//遍历list获取符合条件的对象的id值,一份存到temp中用作递归的参数,并存到全局变量中用来获取所有符合条件的idfor (SysEnterpriseOrg s:sysEnterpriseOrgList) {temp.add(s.getId());result.add(s.getId());}}if(temp.size()!=0&&temp!=null){selectChild(temp);}}

 

单元测试调用示例:

package com.ws.test.common;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ws.sys.entity.SysEnterpriseOrg; import com.ws.sys.mapper.SysEnterpriseOrgMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration;import java.util.ArrayList; import java.util.List;/*** Created by HAOHAO on 2019/6/18.*/ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @WebAppConfiguration public class diguiTest  {@Autowiredprivate SysEnterpriseOrgMapper sysEnterpriseOrgMapper;List<Long> result = new ArrayList<Long>();@Testpublic void test(){List<Long> canshu = new ArrayList<Long>();canshu.add(1l);selectChild(canshu);for (Long s :result) {System.out.print(s);}}public void selectChild(List<Long> ids){//用来存取调用自身递归时的参数List<Long> temp= new ArrayList<Long>();//查询数据库中对应id的实体类List<SysEnterpriseOrg> sysEnterpriseOrgList = new ArrayList<SysEnterpriseOrg>();//遍历传递过来的参数idsfor (Long id :ids) {//查询子级架构//此处使用mybaatisPlus的条件构造器,查询pid等于id的对象QueryWrapper<SysEnterpriseOrg> sysEnterpriseOrgChildQueryWrapper = new QueryWrapper<SysEnterpriseOrg>();sysEnterpriseOrgChildQueryWrapper.eq("pid",id.toString());//查询结果返会一个listsysEnterpriseOrgList= sysEnterpriseOrgMapper.selectList(sysEnterpriseOrgChildQueryWrapper);//遍历list获取符合条件的对象的id值,一份存到temp中用作递归的参数,并存到全局变量中用来获取所有符合条件的idfor (SysEnterpriseOrg s:sysEnterpriseOrgList) {temp.add(s.getId());result.add(s.getId());}}if(temp.size()!=0&&temp!=null){selectChild(temp);}} }

 


 

总结

以上是生活随笔为你收集整理的Java中使用递归算法实现子级架构的查询的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。