该接口是我们查询出所有的结点个子节点,在查询的时候利用父节点parentId
属性来进行递归查询,当子节点不再有的时候,我们就结束递归查询,然后将查询到的结果全部返回给客户端。关于在首先我们判断登陆者是否是管理员,我们在10、【分类模块管理】——添加分类接口开发有说明。controller
:
//查询当前节点和子节点
@RequestMapping("get_children_category.do")
@ResponseBody
public ServerResponse getCategoryAndDeepChildrenCategory(HttpSession session,@RequestParam(value = "categoryId",defaultValue ="0" )Integer categoryId){
//验证用户是否登录
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请先登录");
}
//校验是否是管理员
if(iUserService.checkAdminRole(user).isSuccess()){
//查询当前节点的Id和递归子节点的Id
return iCategoryService.selectCategoryAndChildrenById(categoryId);
}else{
return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
}
}
server
:
//递归查询查询该节点和子节点的Id
ServerResponse selectCategoryAndChildrenById(Integer categoryId);
serverImpl
:
/**
* 递归查询查询该节点和子节点的Id
* @param categoryId
* @return
*/
public ServerResponse selectCategoryAndChildrenById(Integer categoryId){
//调用递归算法
Set<Category> categorySet= Sets.newHashSet();
finChildCategory(categorySet,categoryId);
List<Integer> categoryIdList= Lists.newArrayList();
if(categoryId !=null){
for(Category categoryItem : categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return ServerResponse.createBySuccess(categoryIdList);
}
//递归算法算出子节点
private Set<Category> finChildCategory(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){
finChildCategory(categorySet,categoryItem.getId());
}
return categorySet;
}
Mapper
:
// 通过父结点查询同级字节点的信息
List<Category> selectCategoryChildrenByParentId(Integer parentId);
Mapper.xml
:
<select id="selectCategoryChildrenByParentId" resultMap="BaseResultMap" parameterType="int">
select
<include refid="Base_Column_List"/>
from mmall_category
where parent_id=#{parentId}
</select>
接口测试: