商品分类
domian
@TableName("t_product_type")
public class ProductType extends Model<ProductType> {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
//父Id
private Long pid;
//子分类
@TableField(exist = false)
private List<ProductType> children =new ArrayList<>();
... ...
}
原方案:递归
1.先获取第一级菜单
2.准备递归的出口
3.递归调用
4.将获取的子菜单设置给父菜单
/**
* @param pid 一级菜单 pid = 0
* @return
*/
public List<ProductType> getAllChildren(Long pid) {
Wrapper<ProductType> wrapper = new EntityWrapper<>();
wrapper.eq("pid", pid);
return productTypeMapper.selectList(wrapper);
}
/**
* 递归函数
* @param pid
* @return
*/
public List<ProductType> treeDataRecursion(Long pid) {
List<ProductType> allChildren = getAllChildren(pid);
//递归出口
if (allChildren == null && allChildren.size() == 0) {
return null;
}
for (ProductType children : allChildren) {
//递归调用
List<ProductType> productTypes = treeDataRecursion(children.getId());
//将子菜单设置给父菜单
children.setChildren(productTypes);
}
return allChildren;
}
@Override
public List<ProductType> treeData() {
return treeDataRecursion(0L);
}
优化方案:组合List集合数据结构
1.定义返回的结果集 List
2.获取所有菜单数据
3.将所有数据存进map集合中 key:Long id ,value:菜单对象
4.组装数据 (详见 :代码 )
5.返回结果集
public List<ProductType> treeDataLoop() {
//最终返回的数据结构
List<ProductType> result = new ArrayList<>();
//所有的分类数据
List<ProductType> allProductTypes = productTypeMapper.selectList(null);
//把所有数据放进map中
Map<Long,ProductType> map =new HashMap<>();
for (ProductType pt : allProductTypes) {
map.put(pt.getId(),pt);
}
//组装数据结构
for (ProductType current : allProductTypes) {
if(current.getPid()==0){
//将一级菜单添加给结果集
result.add(current);
}else {
//通过pid找到父级菜单
ProductType parent = map.get(current.getPid());
//将自己添加进父级菜单
parent.getChildren().add(current);
}
}
return result;
}
@Override
public List<ProductType> treeData() {
return treeDataLoop();
}