一、查找某个节点下的所有节点(下一层平级)
>传入parentId,查找下面一层的所有parentId为指定值的节点。
@Override public ServerResponse getChildrenParallelCategory(Integer categoryId){ if (categoryId == null){ return ServerResponse.createByErrorMsg("参数错误"); } List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId); if (CollectionUtils.isEmpty(categoryList)){ logger.info("未找到当前分类的子类"); } return ServerResponse.createBySuccess(categoryList); }
二、递归查找某个节点下的所有节点
//递归算法,算出子节点 //注意:此处 用Set去重Category,需要对Category重写Hashcode和equals方法 public Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId){ Category category = categoryMapper.selectByPrimaryKey(categoryId); if (category != null){ categorySet.add(category); } //递归查找子节点 List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId); for (Category categoryItem:categoryList) { findChildCategory(categorySet, categoryItem.getId()); } return categorySet; }
三、使用Set去重的时候,需要考虑到HashCode问题,对里面类型进行重写HashCode和equals方法
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Category category = (Category) o; return !(id != null ? !id.equals(category.id) : category.id != null); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; }