树形数据结构的级联查询(子查询、递归)

说明:
当一张表中同时存在id和pid(parent id),我们需要用子连接查出其中的级联关系,并将数据展示为多级列表(树形数据结构),参考以下查询的方法。

1.表结构展示说明

在这里插入图片描述pid是当前行的父节点,这里pid=0是顶级父节点

2.controller代码

    @Autowired
    public CourseTypeServiceImpl courseTypeService;
    /**
     * 查询课程类型的树形结构,多级菜单数据
     * @return
     */
    @GetMapping("/treeData")
    public AjaxResult getTreeData() {
        return courseTypeService.getTreeData();
    }

3.service层代码

    @Override
    public AjaxResult getTreeData() {
    	// 这里使用的是mybatis-plus,basemapper也可以换成对应的CourseTypeMapper
        List<CourseType> courseTypes = baseMapper.selectForTreeData();
        return AjaxResult.me().setResultObj(courseTypes);
    }

4.mapper层代码

public interface CourseTypeMapper extends BaseMapper<CourseType> {
    //查询出课程类型的多级联动表单树形结构,执行的第一条是pid=0 (sql语句中直接写的,这里顶级目录的值为0)
    List<CourseType> selectForTreeData();
}

5.对应的sql语句

注意:
sql语句中引入了一个字段"children",需要在实体类中添加声明这个字段。

	@TableField(exist = false) //当新增表中没有的字段的时候,需要加上这个注解
    private List<CourseType> children;
<mapper namespace="cn.itsource.hb.mapper.CourseTypeMapper">
    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="cn.itsource.hb.domain.CourseType">
        <id column="id" property="id" />
        <!--嵌套子查询:查询当前分类下的子分类列表 :1037
            下面的sql:cn.itsource.hrm.mapper.CourseTypeMapper.selectByPid 是重点。相当于在查询返回的结果
            是当前map类型时,它会自动将查询出来的每一条数据的column="id"作为查询条件,来执行指定的select语句

            property :对应的 type="cn.itsource.hrm.domain.CourseType"中的属性值。
                    将collection查询出来的结果 ,保存到 CourseType中的指定属性中
            ofType : 当前collection执行之后,返回的集合中的对象类型
            column : 表中的字段的值作为select的查询条件
            select : 当前collection将要执行的sql语句(支持2种传入方式:
                1. Sql语句;
                2. 当前mapper.xml文件中的某一个select的id)
        -->
        <collection property="children"
                    ofType="cn.itsource.hb.domain.CourseType"
                    column="id"
					select="cn.itsource.hb.mapper.CourseTypeMapper.selectByPid" />

    </resultMap>

    <select id="selectByPid" resultMap="BaseResultMap">
        select * from t_course_type where pid = #{pid}
    </select>

    <!-- 查出顶级目录,顶级目录的pid=0,再递归查出各级子目录 -->
    <select id="selectForTreeData" resultMap="BaseResultMap">
        select * from t_course_type where pid = 0
    </select>
</mapper>

6.查出的数据前端展示的效果

一级一级的层级关系如下
在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐