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

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

说明:
当一张表中同时存在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.查出的数据前端展示的效果

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

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值