13、【分类模块管理】——查询节点和递归查找功能开发

该接口是我们查询出所有的结点个子节点,在查询的时候利用父节点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>

接口测试:


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,105评论 2 89
  • 风吹着, 越来越紧。 院子里晾晒的衣物, 七零八落—— 偷食的小猫, 怖起了跳跃, 爪子死死地, 死死地啃住地窝;...
    植尚淇阅读 1,787评论 5 5
  • 妈呀,心里好慌,连续几天睡5个小时。这样的情况出现在高考,找工作,还有第二次工作面对找对象的压力的时候。那时候是对...
    onetwo3go阅读 1,560评论 0 0