java关于菜单树,部门树,递归算法(两种)
@RestController
前端跟后端哪个就业难@RequestMapping("department")
public class DepartmentController {
@Resource
IDepartmentServiceInter departmentService;
/**
* 查询所有部门树形展⽰所有部门包含模糊查詢
*
* @return
*/
@RequestMapping("/treelist")
public Object selectAll() {
ModelMap map = new ModelMap();
try {
List<Department> deptDtos = departmentService.selectNull(null);//查询所有根节点
List<Department> deptDtosNotNull = departmentService.selectNotNull();//查询所有⾮跟节点
for (Department deptDto : deptDtos) { //遍历根节点把递归出来的⼦节点集合插⼊⽗节点
List<Department> departmentList = getDepartmentList(deptDtosNotNull, Departmentcode());
deptDto.setChildDept(departmentList);
}
map.put("msg", "查询部门成功");
map.put("data", deptDtos);
map.put("code", 0);
} catch (Exception e) {
e.printStackTrace();
map.put("msg", "查询部门失败");
map.put("code", 1);
}
return map;
}
//
private List<Department> getDepartmentList(List<Department> departmentList, String pId) {
List<Department> list = new ArrayList<>();
//遍历⾮跟节点
for (Department department : departmentList) {
//获取⾮跟节点的code
String departmentcode = Departmentcode();
//获取⾮跟节点的pId
String updepartmentcode = Updepartmentcode();
if (StringUtils.isNotBlank(updepartmentcode)) { //如果pId不为空
if (updepartmentcode.equals(pId)) {      //如果当前节点等于⽗节点id,证明下⾯还有节点,再递归查询出该节点下的⼦节点                    List<Department> departments = getDepartmentList(departmentList, departmentcode);
department.setChildDept(departments);
list.add(department);
}
}
}
return list;
}
}
domain实体类
package com.kevin.demo.domain;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Department {
private String departmentcode;//部门code
private String departmentname;//部门名称
private String updepartmentcode="0";//上级部门
private List<Department> childDept =new ArrayList();//部门信息树
public Department() {
}
}
mybatis  sql  mxl⽂件
<select id="selectAll" resultType="department">
select * from department
</select>
<select id="selectNotNull" resultType="department">
select * from department where updepartmentcode is not null
</select>
service业务层 与实现类
public interface IDepartmentServiceInter {
public List<Department> selectNull(String departmentcode);
List<Department> selectNotNull();
}
-
-----------------------------------------------------------------------------------------
@Service
public class DepartmentImpl implements IDepartmentServiceInter {
@Resource
DepartmentMapper departmentMapper;
@Override
public List<Department> selectNull(String departmentcode) {
return departmentMapper.selectDepartmentTrees(departmentcode);    }
@Override
public List<Department> selectNotNull() {
List<Department> list = departmentMapper.selectNotNull();
return list;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。