Mybatis正向和反向递归查询详解

本文详细介绍如何使用Mybatis的Mapper.xml实现递归查询,包括正向递归和反向递归查询机构部门树信息的具体配置和代码示例。

简介

在日常的程序开发中,难免会遇到查询递归查询,如目录树等查询,大部分程序猿会选择使用foreach或while进行递归查询,今天,我来介绍Mybatis的Mapper.xml方式实现递归查询。

递归数据

DeptDTO.class

@Data
@ApiModel("部门列表DTO")
public class DeptDTO {
    /**
     *  部门编号
     */
    private int id;

    /**
     *  部门名称
     */
    private String name;

    /**
     *  上级单位 -1:根节点
     */
    private int pId;

    /**
     *  状态 1:可用 0:不可用
     */
    private char status;

    /**
     *  备注
     */
    private String remark;

    private DeptDTO deptDTO;
}

正向递归

这里,使用机构部门来进行案例讲解。

	<!--根据机构编号,查询其所在的所有下级部门树信息-->
    <select id="getDeptTreeById" parameterType="int" resultMap="getParent">
        select id,`name`,p_id,status,remark from common_dept t where p_id = #{p_id}
    </select>

    <resultMap id="getParent" type="com.dc.blank.entity.dto.DeptDTO">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="p_id" property="pId"></result>
        <result column="status" property="status"></result>
        <result column="remark" property="remark"></result>
        <collection property="deptDTO" select="getDeptTreeById" column="id"></collection>
    </resultMap>
  • id=“getDeptTreeById” 主查询语句
  • parameterType=“int” 传入参数类型
  • resultMap=“getParent” 递归查询语句
  • type=“com.dc.blank.entity.dto.DeptDTO” 返回的DTO展示数据
  • collection property=“deptDTO” select=“getDeptTreeById” column=“id” 将查询的p_id,作为p_id继续执行主查询语句

反向递归

这里,使用机构部门来进行案例讲解。

	<!--根据部门编号,查询其所在的所有上级机构树信息-->
    <select id="getDeptTreeById" parameterType="int" resultMap="getParent">
        select id,`name`,p_id,status,remark from common_dept t where id = #{id}
    </select>

    <resultMap id="getParent" type="com.dc.blank.entity.dto.DeptDTO">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="p_id" property="pId"></result>
        <result column="status" property="status"></result>
        <result column="remark" property="remark"></result>
        <collection property="deptDTO" select="getDeptTreeById" column="p_id"></collection>
    </resultMap>
  • id=“getDeptTreeById” 主查询语句
  • parameterType=“int” 传入参数类型
  • resultMap=“getParent” 递归查询语句
  • type=“com.dc.blank.entity.dto.DeptDTO” 返回的DTO展示数据
  • collection property=“deptDTO” select=“getDeptTreeById” column=“p_id” 将查询的id,作为id继续执行主查询语句

总结

正向递归和反向递归,主要的配置不同在于主查询语句的查询条件和复合查询语句里collection的column

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值