由於部門的層級不可控,因此如果我想要獲取所有部門的完整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
}
]
