递归查询表结构

  • 对于业务逻辑的编写我们大都是对于数据库表的增删改查,但是遇到特殊的查询也会涉及到算法的应用,例如在查询一个行业字典表的时候我们的需求就是要获取到整个行业的信息,这是一个典型的树形关系,节点就是Industry这个entity,它的子分类是一个list,我们可以定义这样的表结构去存储行业的信息。

这里写图片描述
最开始考虑到我们实际的应用情况貌似只有二级所以只用了两层就用了两层循环去遍历,但是后来我考虑到以后细分的可能性,还是打算用树形去递归遍历。

public IndustryListResp getIndustryList() throws TException {
        IndustryCategoryExample industryCategoryExample = new IndustryCategoryExample();
        // 查询出所有父节点
        industryCategoryExample.or().andParentCodeEqualTo(0);
        List<IndustryCategory> industris = industryCategoryService.getIndustryByExample(industryCategoryExample);
        List<Industry> industryList = new ArrayList<Industry>();
        for (IndustryCategory ic : industris) {
            Industry industry = new Industry();
            industry.setCode(ic.getCode());
            industry.setName(ic.getName());
            industry.setData(getIndustryByCode(ic.getCode()));
            industryList.add(industry);
        }
        IndustryListResp resp = new IndustryListResp();
        resp.setIndustries(industryList);
        return resp.setError(new Response().setError(new GeError()).setSuccess(true));
    }
// 根据顶级行业分类递归查询子行业
    private List<Industry> getIndustryByCode(int code) {
        IndustryCategoryExample industryCategoryExample = new IndustryCategoryExample();
        industryCategoryExample.or().andParentCodeEqualTo(code);
        List<IndustryCategory> industryCategoryList = industryCategoryService
                .getIndustryByExample(industryCategoryExample);
                // 递归入口
        if (industryCategoryList != null && industryCategoryList.size() != 0) {
            List<Industry> industryList = new ArrayList<Industry>();
            for (IndustryCategory ic : industryCategoryList) {
                Industry industry = new Industry();
                industry.setCode(ic.getCode());
                industry.setName(ic.getName());
                industry.setData(getIndustryByCode(ic.getCode()));
                industryList.add(industry);
            }
            return industryList;
        } else // 递归出口
            return new ArrayList<Industry>();
    }

优雅的完成了对应数据结构的遍历。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值