Java-递归查询部门下所有子部门(包括本部门),会得到一个部门id的集合:List
deptIds
具体代码如下:
//递归1
public List<Long> queryAllSubInstitutionIds(Long institutionId) {
List<Long> subInstitutionIds = new ArrayList<>();
querySubInstitutionIds(institutionId, subInstitutionIds);
return subInstitutionIds;
}
//递归2
private void querySubInstitutionIds(Long institutionId, List<Long> subInstitutionIds) {
// 添加当前机构ID
subInstitutionIds.add(institutionId);
// 获取当前机构的子机构
List<Long> childrenIds = deptList(institutionId);
// 递归查询子机构的子机构
for (Long deptId : childrenIds) {
querySubInstitutionIds(deptId, subInstitutionIds);
}
}
//递归3
private List<Long> deptList(Long deptId){
List<Long> list=baseMapper.getDeptList(deptId);
return list;
}
其中:baseMapper.getDeptList()方法,查询数据库数据,代码如下:
/**
* 查询机构下子机构
* @param deptId
* @return
*/
List<Long> getDeptList(Long deptId);
sql如下:
select dept_id
from sys_dept
where del_flag = 0
and status = 0
and parent_id = #{deptId}
表结构如下:
拿到部门id list之后,代码如下:
1.接口方法:
params.put("deptIds",deptIds);
classUserList = baseMapper.getUserListByAllDept(params);
2.dao:
/**
* 查询机构下所有子机构的学生
* @param params
* @return
*/
List<ClassStudentListVO> getUserListByAllDept(Map<String, Object> params);
3.sql:
select
A.user_id,
A.user_name,
A.nick_name,
A.phonenumber,
A.status,
A.sex,
B.dept_name,
C.grade,
C.school,
C.lessons,
C.lessons30
from
sys_user A
left join sys_dept B ON A.dept_id=B.dept_id
left join student_info C ON A.user_id=C.user_id
<where>
A.del_flag=0 and A.user_type=1 and A.status=0
and B.del_flag=0
and C.is_del=0
<if test="deptIds != null">
AND A.dept_id in
<foreach collection="deptIds" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
<if test="nickName != null and nickName.trim() != ''">
AND A.nick_name like concat('%',#{nickName},'%')
</if>
<if test="sex != null and sex.trim() != ''">
AND A.sex=#{sex}
</if>
<if test="phoneNumber != null and phoneNumber.trim() != ''">
AND A.phonenumber=#{phoneNumber}
</if>
</where>
其中,主要sql如下:
<if test="deptIds != null">
AND A.dept_id in
<foreach collection="deptIds" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
标签:deptId,Java,递归,subInstitutionIds,List,dept,部门,user,id
From: https://www.cnblogs.com/xiaoguo-java/p/18617891