【編程】Mybatis遞歸

如果我們在數據庫表中以類似如下的結構來保存樹形結構:

id parent_id name
1 0 X市
2 1 X市A區
3 1 X市B區
4 2 X市A區1街

同時又想要簡短的遞歸來把數據組裝成樹形結構,那麼以下是兩個簡短示例:

<resultMap id="organizationTreeResp" type="com.pingan.pcloud.lg.info.vo.resp.system.OrganizationTreeResp">
    <id column="id" property="id"/>
    <collection column="id" property="children" select="withAuthorityGetOrganizationTree"/>
</resultMap>

<select id="withAuthorityGetOrganizationTree" parameterType="long" resultMap="organizationTreeResp">
    select * from auth_organization o WHERE o.is_del = 0 /*and o.*/ AND o.parent_id = #{id}
</select>
List<OrganizationTreeResp> withAuthorityGetOrganizationTree(@Param("id") Long id);
<resultMap id="permissionResp" type="com.pingan.pcloud.lg.info.vo.resp.system.PermissionResp">
    <id column="id" property="id"/>
    <collection column="{roleId=roleId, id=id}" property="childrenPermission" select="getPermissionTree"/>
</resultMap>

<select id="getPermissionTree" resultMap="permissionResp">
    select o.*, #{roleId} roleId, 
        (CASE WHEN (EXISTS (SELECT 1 FROM auth_role_permission rp
        WHERE rp.role_id = #{roleId} AND rp.permission_id = o.id)) THEN 1 ELSE 0 END) doesHaveThePermission
    from auth_permission o WHERE o.is_del = 0 AND o.parent_id = #{id}
</select>
ArrayList<PermissionResp> getPermissionTree(@Param("id") Integer id, @Param("roleId") Integer roleId);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章