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>

结果展示:

相关推荐
吃饱了得干活5 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
lwx572807 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
Flynt8 小时前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
plainGeekDev9 小时前
Activity 间传值 → Navigation 参数
android·java·kotlin
plainGeekDev9 小时前
onActivityResult → ActivityResult API
android·java·kotlin
Sunia9 小时前
《AgentX 专栏》10-生产部署:3台2C4G云服务器把企业级Agent真正跑起来的完整方案
java·架构
ZhengEnCi10 小时前
J7A-高级Java工程师面试三道灵魂拷问-深度广度与工程素养的终极检验
java·后端
狼爷1 天前
吃透 Java Function 接口,搞定 99% 的 Stream 场景
java·函数式编程
祎雪双十Gy1 天前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java12341 天前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java