Java中使用递归算法实现子级架构的查询
生活随笔
收集整理的這篇文章主要介紹了
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中使用递归算法实现子级架构的查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot+Junit在IDE
- 下一篇: Java中使用递归算法实现查找树形结构中