需求:不要在数据库层写存储过程或者调用数据库自带方法实现,因为数据库有可能是MySQL或者是oracle。
核心递归代码:
/**
* @Description: 递归查询机构
* @param @param departList
* @param @param departId 设定文件
* @return void 返回类型
* @throws
*/
private void getDepartmentList(List<SysDepartment> departList, Integer departId) {
try {
List<SysDepartment> list = departmentService.getDListByParentId(departId);
if (null != list && list.size()>0) {
for (int i = 0; i < list.size(); i++) {
SysDepartment department = list.get(i);
departList.add(department);
getDepartmentList(departList, department.getDepartId());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
调用代码:
List<SysDepartment> departList = departmentService.getDListByParentId(Integer.parseInt(departId));
if (null != departList && departList.size() > 0) {
SysDepartment department = departList.get(0);
getDepartmentList(departList, department.getDepartId());
returnCode = Const.RETURN_CODE_1;
map.put("department", departList);
}
SQL:
-- ----------------------------
-- Table structure for `SYS_DEPARTMENT`
-- ----------------------------
DROP TABLE IF EXISTS `SYS_DEPARTMENT`;
CREATE TABLE `SYS_DEPARTMENT` (
`DEPART_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '机构ID',
`DEPART_NAME` varchar(20) DEFAULT NULL COMMENT '机构名称',
`PARRENT_ID` int(11) DEFAULT NULL COMMENT '上级ID',
`DEPART_CODE` varchar(20) DEFAULT NULL,
`DEPART_DESC` text,
PRIMARY KEY (`DEPART_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COMMENT='组织机构表';
-- ----------------------------
-- Records of `SYS_DEPARTMENT`
-- ----------------------------
BEGIN;
INSERT INTO `SYS_DEPARTMENT` VALUES ('1', '中国电子', '0', null, null), ('2', '子公司1', '1', null, null), ('3', '子公司2', '1', null, null), ('4', '子部门1', '2', null, null), ('5', '子部门2', '2', null, null), ('6', '子部门3', '2', null, null), ('7', '子部门4', '2', null, null), ('8', '科室1', '4', null, null), ('9', '科室2', '4', null, null);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;