- 对于业务逻辑的编写我们大都是对于数据库表的增删改查,但是遇到特殊的查询也会涉及到算法的应用,例如在查询一个行业字典表的时候我们的需求就是要获取到整个行业的信息,这是一个典型的树形关系,节点就是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>();
}
优雅的完成了对应数据结构的遍历。