分析实现:
for循环 查询数据库不可取
先将数据全部查询出 以节点CODE作为key,节点数据做为value 封装为Map结构数据
以叶子节点为起点 ,获取其父级节点 ,遍历查询,注意死循环问题
逻辑实现:
方案一:采用栈实现
public static Stack<Product> collectProductHierarchyInfo(String productPk, Map<String, Product> productDirectoryInfo) { Stack<Product> productHierarchy = new Stack<>(); Product lastStageProductInfo = productDirectoryInfo.get(productPk); if (null == lastStageProductInfo) { return productHierarchy; } List<String> deadCycle = new ArrayList<>(); deadCycle.add(productPk); productHierarchy.push(lastStageProductInfo); String parentPk = lastStageProductInfo.getPk_parent(); while (StringUtil.isNotEmpty(parentPk)) { Product superiorProductInfo = productDirectoryInfo.get(parentPk); if (null == superiorProductInfo) { break; } deadCycle.add(parentPk); productHierarchy.push(superiorProductInfo); parentPk = superiorProductInfo.getPk_parent(); if (deadCycle.contains(parentPk)) { break; } } return productHierarchy; }
方案二:
public static List<Product> collectProductHierarchyInfo(String productPk, Map<String, Product> productDirectoryInfo) { List<Product> productHierarchy = new ArrayList<>(); Product lastStageProductInfo = productDirectoryInfo.get(productPk); if (null == lastStageProductInfo) { return productHierarchy; } List<String> deadCycle = new ArrayList<>(); deadCycle.add(productPk); productHierarchy.add(lastStageProductInfo); String parentPk = lastStageProductInfo.getPk_parent(); while (StringUtil.isNotEmpty(parentPk)) { Product superiorProductInfo = productDirectoryInfo.get(parentPk); if (null == superiorProductInfo) { break; } deadCycle.add(parentPk); productHierarchy.add(superiorProductInfo); parentPk = superiorProductInfo.getPk_parent(); if (deadCycle.contains(parentPk)) { break; } } Collections.reverse(productHierarchy); return productHierarchy; }