简介
在日常的程序开发中,难免会遇到查询递归查询,如目录树等查询,大部分程序猿会选择使用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