递归查询树形结构--mybatisplus查询

430 阅读1分钟

树结构查询,本质上还是用了递归的算法

在开发中,树结构查询是经常用到的,并且在面试中,经常会问到创建一个树形结构的数据表,该如何操作等问题。今天准备分享一下树形结构的创建和查询方式。

本文是利用ORM框架mybatisplus查询创建树形结构

表结构

idnamecodeparentIdis_del
1A集团100
2B公司210
3C部门320

如果创建树形结构,在数据表中必须存在parentid,记录的就是父节点的ID

实体类

//关联数据表
@TableName("dept")
public class DeptTree implements Serializable {

    private static final long serialVersionUID = 1L;
    //设置关联主键ID,并且设置自增
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @ApiModelProperty("名称")
    private String name;

    @ApiModelProperty("父部门id")
    private Long parentId;

    @ApiModelProperty("编码")
    private String code;

    @ApiModelProperty("是否删除")
    private Integer isDel;
}

类中涉及到几个mybatisplus的注解,@TableName,@TableId。后续会专门出一期mybatis,mybatisplus的详细介绍

Mapper

@Mapper
public interface DeptMapper extends BaseMapper<Dept> {

    List<DeptTree> getList(Map<String,String> map);

}

xmlMapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.system.mapper.DeptMapper">
    //一级查询
    <resultMap id="DeptResult" type="com.test.system.entity.Dept">
        <id property="deptId" jdbcType="VARCHAR" column="dept_id"/>
        <result property="deptName" jdbcType="VARCHAR" column="dept_name"/>
    </resultMap>
    //子查询
    <resultMap id="DeptTreeResult" type="com.test.system.entity.vo.DeptTree" extends="DeptResult">
        <collection property="children" column="dept_id" javaType="java.util.ArrayList" ofType="com.test.system.entity.Dept" select="getTreeDept"/>
    </resultMap>

    <sql id="deptPid">
        <if test="pid != null and pid != ''">
            and parent_id = #{#pid}
        </if>
    </sql>

    <select id="getTreeDept" resultMap="DeptResult">
        select *
        from dept
        where is_del = '0'
        and pid = #{pid};
    </select>

    <select id="getList" parameterType="map" resultMap="DeptTreeResult">
        select *
        from dept
        where is_del = '0'
          <include refid="deptPid"></include>
    </select>
</mapper>

先通过一级查询,查询所有高级节点。然后通过子查询,条件是parentid=id查询对应子节点。