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>

结果展示:

相关推荐
xdscode13 分钟前
SpringBoot ThreadLocal 全局动态变量设置
java·spring boot·threadlocal
lifallen16 分钟前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
丶小鱼丶24 分钟前
链表算法之【合并两个有序链表】
java·算法·链表
张先shen1 小时前
Elasticsearch RESTful API入门:全文搜索实战(Java版)
java·大数据·elasticsearch·搜索引擎·全文检索·restful
天河归来2 小时前
springboot框架redis开启管道批量写入数据
java·spring boot·redis
张先shen2 小时前
Elasticsearch RESTful API入门:全文搜索实战
java·大数据·elasticsearch·搜索引擎·全文检索·restful
codervibe2 小时前
如何用 Spring Security 构建无状态权限控制系统(含角色菜单控制)
java·后端
codervibe2 小时前
项目中如何用策略模式实现多角色登录解耦?(附实战代码)
java·后端
TCChzp2 小时前
synchronized全链路解析:从字节码到JVM内核的锁实现与升级策略
java·jvm
大葱白菜2 小时前
🧩 Java 枚举详解:从基础到实战,掌握类型安全与优雅设计
java·程序员