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

数据库表设计

给每条数据加个 parent_id字段,通过parent_id来建立数据之间的父子(层级)关系。
这里写图片描述
parent_id为0是根节点。
看下面这些数据感受一下他们之间通过parent_id建立起的关系
这里写图片描述

数据库查询语句

通过父节点id查询出同级的节点

<select id="selectChildrenCategoryByParentId" resultMap="BaseResultMap" parameterType="int">
      select
      <include refid="Base_Column_List"/>
      from mmall_category
      where parent_id = #{parentId}
</select>

service层代码实现

//这里使用Set集合来存储查询出的数据,因为查询出的数据可能会重复,使用Set可以处理复杂对象去重
private Set<Category> findChildCategory(Set<Category> categorySet,Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if(category != null){
            categorySet.add(category);
        }
        //查找子节点,递归算法一定要有一个退出的条件。
        //如果有子节点则递归下去,直到以子节点的id作为parent_id时没有查询出数据时,递归结束,返回上级节点。去继续递归其他的节点
        List<Category> categoryList = categoryMapper.selectChildrenCategoryByParentId(categoryId);
        for(Category categoryItem:categoryList){
            findChildCategory(categorySet,categoryItem.getId());
        }
        return categorySet;
 }

Category实体类

注意点根据id重写equals和hashCode方法

import java.util.Date;

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;

    public Category(Integer id, Integer parentId, String name, Boolean status, Integer sortOrder, Date createTime, Date updateTime) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
        this.status = status;
        this.sortOrder = sortOrder;
        this.createTime = createTime;
        this.updateTime = updateTime;
    }

    public Category() {
        super();
    }

    //get、set方法 此处忽略... 

    //根据id重写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 id != null ? id.equals(category.id) : category.id == null;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}

欢迎关注博主公众号。在这里你可以收获一个java后端学习的环境,一个问答的学习环境。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/a1102325298/article/details/80835103
今日推荐