递归查询

137 阅读1分钟

在做项目时,部门间经常会出现从属关系,而我们在查询末节的部门时可以运用递归的方法,巧妙地达到效果,此处记录一下。

      <resultMap id="DepartmentWithChildren" type="com.lunlunbu.server.pojo.Department" extends="BaseResultMap">
        <collection property="children" ofType="com.lunlunbu.server.pojo.Department" 
        select="com.lunlunbu.server.mapper.DepartmentMapper.getAllDepartments" column="id">

        </collection>
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, name, parentId, depPath, enabled, isParent
    </sql>
    <!-- 获取所有部门-->
    <select id="getAllDepartments" resultMap="DepartmentWithChildren">
        select
        <include refid="Base_Column_List" />
        from t_department
        where parentId=#{parentId}
    </select>

此处我给每个部门添加了id,添加了一个parentId来标记其所属部门,以及depPath为其所有的部门。 通过判断parentId找到部门(可能有多个),查询到当前部门id,将id作为parentId递归传入方法,实现递归查询