设计及封装无限层级的树状结构

设计及封装无限层级的树状结构

需求:电商项目中,在商品的品类管理模块,会涉及到递归调用出该节点的所有子节点的操作。

数据表设计:

设计及封装无限层级的树状结构_第1张图片

Category:

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;

    @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;
    }
}

Controller:

/**
 * 根据传的categoryId获取当前categoryId下边节点的category信息(平级,无递归)
 * @param session
 * @param categoryId
 * @return
 */
@RequestMapping("get_category.do")
@ResponseBody
public ServerResponse getChildrenParallelCategory(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()){
        //查询子节点的category信息,并且不递归,保持平级
        return iCategoryService.getChildrenParallelCategory(categoryId);
    }else {
        return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
    }
}


/**
 * 获取当前的categoryId并且递归查询它的子节点的categoryId
 * @param session
 * @param categoryId
 * @return
 */
@RequestMapping("get_deep_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("无权限操作,需要管理员权限");
    }
}

ServiceImpl:

@Override
public ServerResponse> getChildrenParallelCategory(Integer categoryId){
    List categoryList = categoryMapper.selectCategoryChildrenParentId(categoryId);
    if(CollectionUtils.isEmpty(categoryList)){
        logger.info("未找到当前分类的子分类");
    }
    return ServerResponse.createBySuccess(categoryList);
}

/**
 * 递归查询本节点的id及其子孙节点的id:获取当前categoryId下的子节点,还要继续查找子节点是否还有子节点,及所有子孙节点
 * 0-->10-->100
 * 如果传0,会返回10和100
 * 如果传10,会返回100
 * @param categoryId
 * @return
 */
@Override
public ServerResponse> selectCategoryAndChildrenById(Integer categoryId){
    HashSet categorySet = Sets.newHashSet();
    findChildCategory(categorySet,categoryId);

    List categoryIdList = Lists.newArrayList();
    if(categoryId!=null){
        for(Category categoryItem : categorySet){
            categoryIdList.add(categoryItem.getId());
        }
    }
    return ServerResponse.createBySuccess(categoryIdList);
}

递归算法:

/**
 * 为了使使用set集合不重复,需要重写hashcode和equals方法
 * 递归算法:算出子节点
 * @param categorySet
 * @param categoryId
 * @return
 */
private Set findChildCategory(Set categorySet,Integer categoryId){
    Category category = categoryMapper.selectByPrimaryKey(categoryId);
    if(category!=null){
        categorySet.add(category);
    }
    //查找子节点,递归算法一定要有一个退出的条件
    List categoryList = categoryMapper.selectCategoryChildrenParentId(categoryId);
    for(Category categoryItem:categoryList){
        findChildCategory(categorySet,categoryItem.getId());
    }
    return categorySet;
}

mapper:

public interface CategoryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Category record);

    int insertSelective(Category record);

    Category selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Category record);

    int updateByPrimaryKey(Category record);

    /**
     * 根据categoryId获取孩子节点的category信息
     * @param parentId
     * @return
     */
    List selectCategoryChildrenParentId(Integer parentId);
}

xml:




  
    
      
      
      
      
      
      
      
    
  
  
    id, parent_id, name, status, sort_order, create_time, update_time
  
  
  
    delete from mmall_category
    where id = #{id,jdbcType=INTEGER}
  
  
    insert into mmall_category (id, parent_id, name, 
      status, sort_order, create_time, 
      update_time)
    values (#{id,jdbcType=INTEGER}, #{parentId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 
      #{status,jdbcType=BIT}, #{sortOrder,jdbcType=INTEGER},now(),
      now())
  
  
    insert into mmall_category
    
      
        id,
      
      
        parent_id,
      
      
        name,
      
      
        status,
      
      
        sort_order,
      
      
        create_time,
      
      
        update_time,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{parentId,jdbcType=INTEGER},
      
      
        #{name,jdbcType=VARCHAR},
      
      
        #{status,jdbcType=BIT},
      
      
        #{sortOrder,jdbcType=INTEGER},
      
      
        now(),
      
      
        now(),
      
    
  
  
    update mmall_category
    
      
        parent_id = #{parentId,jdbcType=INTEGER},
      
      
        name = #{name,jdbcType=VARCHAR},
      
      
        status = #{status,jdbcType=BIT},
      
      
        sort_order = #{sortOrder,jdbcType=INTEGER},
      
      
        create_time = #{createTime,jdbcType=TIMESTAMP},
      
      
        update_time = now(),
      
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update mmall_category
    set parent_id = #{parentId,jdbcType=INTEGER},
      name = #{name,jdbcType=VARCHAR},
      status = #{status,jdbcType=BIT},
      sort_order = #{sortOrder,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = now()
    where id = #{id,jdbcType=INTEGER}
  

  

你可能感兴趣的:(JavaEE)