Controller:
/*获取当前categoryId,并且递归查询他的子节点的categoryID*/
@RequestMapping("get_deep_category.do")
@ResponseBody
public ServerResponse getCategoryAndDeepChildrenCatgory(HttpSession session,@RequestParam(value ="categoryId" ,defaultValue = "0") Integer categoryId){
User user=(User) session.getAttribute(Const.CURRENT_USER);
if(user==null){
return ServerResponse.creatByErrorCodeMessgae(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
}
if(iUserService.checkAdminRole(user).isSuccess()){
//是管理员===>查询当前节点的id和递归子节点的id: 0--->1000--->100000
return iCategoryServerice.selectCargoryAndChildById(categoryId);
}else{
return ServerResponse.creatByErrorMessgae("无权处理,需要管理员权限");
}
}
Service:
/*
* 递归查询本节点的id和其孩子节点的id
* */
@Override
public ServerResponse selectCargoryAndChildById(Integer categoryId){
Set<Category> categorySet= Sets.newHashSet();
findChildCategory(categorySet,categoryId);
List<Integer> categoryIdList= Lists.newArrayList();
if(categoryId!=null){
for(Category categoryItem:categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return ServerResponse.creatBySuccess(categoryIdList);
}
//递归函数(供ServerResponse使用)
private 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 categoryIitem:categoryList){
findChildCategory(categorySet,categoryIitem.getId());
}
return categorySet;
}
实体类重写.equals和hashcode方法:
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(id, category.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
注意:上面class为红色是因为这些class未上传git而不是报错