使用mybatis實現遞歸查詢


由於部門的層級不可控,因此如果我想要獲取所有部門的完整json的話,就要采用遞歸調用,這里的遞歸調用我們可以利用MyBatis的ResultMap中的collection實現,核心代碼如下:

<resultMap id="BaseResultMap" type="org.sang.bean.Department">
    <id property="id" column="id"/>
    <result column="name" property="name"/>
    <result column="parentId" property="parentId"/>
    <result column="isParent" property="isParent"/>
    <collection property="children" ofType="org.sang.bean.Department" select="org.sang.mapper.DepartmentMapper.getDepByPid" column="id">
    </collection>
</resultMap>
<select id="getDepByPid" resultMap="BaseResultMap">
    select d1.*from department d1 where d1.`parentId`=#{pid} AND d1.enabled=true;
</select>

每一個Department中都有一個children屬性,getDepByPid方法的返回結果是一個BaseResultMap,BaseResultMap中的collection又將調用getDepByPid方法,通過這種方式我們可以快速實現一個遞歸調用。Mapper中只需要定義如下方法即可:

List<Department> getDepByPid(Long pid);

查詢結果如下(部分):

[
    {
        "id": 1,
        "name": "股東會",
        "parentId": -1,
        "enabled": true,
        "children": [
            {
                "id": 4,
                "name": "董事長",
                "parentId": 1,
                "enabled": true,
                "children": [
                    {
                        "id": 5,
                        "name": "總經理",
                        "parentId": 4,
                        "enabled": true,
                        "children": [
                            {
                                "id": 8,
                                "name": "財務部",
                                "parentId": 5,
                                "enabled": true,
                                "children": [],
                                "parent": false
                            }],
                        "parent": true
                    }
                ],
                "parent": true
            }
        ],
        "parent": true
    }
]

摘自:
https://github.com/lenve/vhr/wiki/13.遞歸查詢與存儲過程調用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM