Java-递归查询部门下所有子部门(包括本部门),会得到一个部门id的集合:List
deptIds
具体代码如下:
//递归1public List<Long> queryAllSubInstitutionIds(Long institutionId) {List<Long> subInstitutionIds = new ArrayList<>();querySubInstitutionIds(institutionId, subInstitutionIds);return subInstitutionIds;}//递归2private void querySubInstitutionIds(Long institutionId, List<Long> subInstitutionIds) {// 添加当前机构IDsubInstitutionIds.add(institutionId);// 获取当前机构的子机构List<Long> childrenIds = deptList(institutionId);// 递归查询子机构的子机构for (Long deptId : childrenIds) {querySubInstitutionIds(deptId, subInstitutionIds);}}//递归3private 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_idfrom sys_deptwhere del_flag = 0and status = 0and 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:
selectA.user_id,A.user_name,A.nick_name,A.phonenumber,A.status,A.sex,B.dept_name,C.grade,C.school,C.lessons,C.lessons30fromsys_user Aleft join sys_dept B ON A.dept_id=B.dept_idleft join student_info C ON A.user_id=C.user_id<where>A.del_flag=0 and A.user_type=1 and A.status=0and B.del_flag=0and 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>