pid查询树形结构

import java.util.List;

public class Type {
    private Integer id;
    private String name;
    private Integer pid;
    private List<Type> children;
    
    // 省略getter和setter方法
    // ...
}
一次查询所有数据,在内存中组装树形结构(更高效)
// 在TypeService中添加
/**
 * 方案二:一次查询所有数据,内存中组装树形结构
 */
public List<Type> getTypeTreeByMemoryAssembly(Integer pid) {
    if (pid == null) {
        pid = 0; // 假设0为顶级分类的pid
    }
    
    // 一次查询所有分类
    List<Type> allTypes = typeMapper.selectAll();
    
    // 调用工具方法组装树形结构
    return buildTree(allTypes, pid);
}

/**
 * 递归组装树形结构
 */
private List<Type> buildTree(List<Type> allTypes, Integer pid) {
    return allTypes.stream()
        .filter(type -> pid.equals(type.getPid()))
        .map(type -> {
            // 递归设置子分类
            type.setChildren(buildTree(allTypes, type.getId()));
            return type;
        })
        .collect(Collectors.toList());
}
查询pid下所有的子id
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class TypeService {
    
    @Autowired
    private TypeMapper typeMapper;
    
    /**
     * 获取指定pid下的所有ID(包括所有层级子分类)
     * @param pid 父分类ID,为null时默认查询顶级分类
     * @return 所有相关ID的列表
     */
    public List<Integer> getAllChildIds(Integer pid) {
        // 处理默认值,假设0为顶级分类的pid
        Integer parentId = (pid == null) ? 0 : pid;
        
        List<Integer> allIds = new ArrayList<>();
        // 递归收集所有ID
        collectChildIds(parentId, allIds);
        
        return allIds;
    }
    
    /**
     * 递归收集子分类ID
     * @param currentPid 当前父分类ID
     * @param idList 用于存储结果的列表
     */
    private void collectChildIds(Integer currentPid, List<Integer> idList) {
        // 查询当前pid的直接子分类ID
        List<Integer> childIds = typeMapper.selectChildIdsByPid(currentPid);
        
        // 遍历子分类ID,添加到结果列表并递归查询其子分类
        for (Integer childId : childIds) {
            idList.add(childId);
            // 递归查询子分类的子分类
            collectChildIds(childId, idList);
        }
    }
}

posted @ 2025-07-30 14:03  亲爱的阿道君  阅读(7)  评论(0)    收藏  举报