变结构创建好后,写代码实现层级菜单
- 1种方式 递归写法(逻辑稍微复杂)
缺点是重复发sql降低性能
- 2方式 优化
/*
* 第二种方式
* 通过嵌套for循环查询 效率也较低
* */
public List<ProductType> getTreeData2() {
//准备一个父类集合
List<ProductType> productTypes = new ArrayList<>();
//先查询出所有得数据在根据数据条件进行分级
List<ProductType> productTypes1 = productTypeMapper.selectList(null);
//遍历出所有得数据
for (ProductType productType : productTypes1) {
//如果pid==0则是最高级分类
if (productType.getPid() == 0) {
productTypes.add(productType);
} else {
//创建一个
ProductType parent = new ProductType();
for (ProductType type : productTypes1) {
//再遍历一次 -判断有pid等于id 有pid等于id的话就是下一级
if (type.getId() == productType.getPid()) {
//将这父级赋值给他
parent = type;
}
}
//创建父集合
List<ProductType> children = parent.getChildren();
//将子数据添加到父集合中
children.add(productType);
}
}
return productTypes;
}
- 最优方法 准备map
/*
* 最优方式
* */
public List<ProductType> getTreeData() {
//准备一个父类集合
List<ProductType> productTypes = new ArrayList<>();
//先查询出所有得数据在根据数据条件进行分级
List<ProductType> productTypes1 = productTypeMapper.selectList(null);
/**
* 准备一个Map 先将所有的数据装入map中
* 在根据条件去取出存入父集合中
*/
Map<Long,ProductType> map = new HashMap<>();
//遍历出所有得数据 存入map中
productTypes1.forEach(e->{
map.put(e.getId(), e);
});
for (ProductType productType : productTypes1) {
//如果pid==0则是最高级分类
if (productType.getPid() == 0) {
productTypes.add(productType);
} else {
//获取父级
ProductType parent = map.get(productType.getPid());
//创建父集合
List<ProductType> children = parent.getChildren();
//将子数据添加到父集合中
children.add(productType);
}
}
return productTypes;
}