Mybatis-子查询-树形结构-一对多【钢镚核恒】

本文介绍了如何使用Java的MyBatis框架,通过子查询来构建部门的树形结构。DepartmentQueryDto类包含了部门ID及子部门列表,DAO接口提供了查询所有部门树和按父ID查询子树的方法。在Mapper XML中定义了resultMap,利用子查询动态加载每个部门的子部门。这种方法有助于高效地组织和检索层次结构数据。
摘要由CSDN通过智能技术生成

简介

子查询:一个实体类中有许多孩子(自己)

上路

  1. 实体类(最好新建一个返回类)

    public class DepartmentQueryDto {
    
        private Long deptId;
    
        /**
         * 子部门
         */
        private List<DepartmentQueryDto> children;
    
        public List<DepartmentQueryDto> getChildren() {
            return children;
        }
    
        public void setChildren(List<DepartmentQueryDto> children) {
            this.children = children;
        }
    
        public Long getDeptId() {
            return deptId;
        }
    
        public void setDeptId(Long deptId) {
            this.deptId = deptId;
        }
    }
    
  2. dao

    // 查询全部树 
    List<DepartmentQueryDto> findTree();
    // 询指定父id的所有树
    List<DepartmentQueryDto> findTreeByParentId();
    
  3. mapper.xml

    <resultMap id="childrenResultMap" type="com.xquant.system.manager.department.dto.DepartmentQueryDto">
        <id property="deptId" column="DEPT_ID" ></id>
        <collection property="children" column="DEPT_ID" select="findTreeByParentId"/>
    </resultMap>
    
    <select id="findTree" resultMap="childrenResultMap">
        select DEPT_ID from TP_SYS_DEPARTMENT where PARENT_DEPT_ID = 0
    </select>
    
    <select id="findTreeByParentId" resultMap="childrenResultMap">
        select DEPT_ID from TP_SYS_DEPARTMENT where PARENT_DEPT_ID = #{DEPT_ID}
    </select>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值