MyBatis递归查询层级关系的树

之前做递归的时候写了那么多java代码发现根本不需要,直接sql就能搞定,直接上代码。

数据:根据parentId查出id,然后把id赋值给parentId,在查处原本parentId下面有哪些级别的数据。
在这里插入图片描述

实体类:这里关键是id,和父级parentId有关联关系。另外加一个children,list元素是本实体类。

/**
 * 部门实体
 */
public class Department implements Serializable {
    private Integer id;
    private String name;
    private Integer parentId;
    private String depPath;
    private Boolean enabled;
    private Boolean isParent;
    private List<Department> children;// 子部门
}

dao层:这里传的是父级parentId

    /**
     * mapper接口
     */
    List<Department> getAllDepartments(Integer parentId);

xml:

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.cdh.server.pojo.Department">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="parentId" property="parentId"/>
        <result column="depPath" property="depPath"/>
        <result column="enabled" property="enabled"/>
        <result column="isParent" property="isParent"/>
    </resultMap>
	<!-- 相当于id=-1 查询的结果id,再用这个id调用自己方法查询 -->
    <resultMap id="DepartmentMap" type="com.cdh.server.pojo.Department" extends="BaseResultMap">
        <collection
                property="children"
                ofType="com.cdh.server.pojo.Department"
                select="com.cdh.server.mapper.DepartmentMapper.getAllDepartments"
                column="id">
        </collection>
    </resultMap>

    <!--查询所有部门-->
    <select id="getAllDepartments" resultMap="DepartmentMap">
    select id, name, parentId, depPath, enabled, isParent
    from t_department
    where parentId = #{parentId}
    </select>

结果展示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值