首先创建一个util包,里面创建一个util类(部门下有子部门...举例)
先获取到顶级部门 from department d where d.parent.id is null; public List<Department> findListChildren(Long parentId) { // TODO Auto-generated method stub String hql = "from Department d where d.parent.id=?"; List<Department> list = getSession().createQuery(hql).setLong(0, parentId).list(); return list; } 然后调用之前写好的util类, 里面有一个方法getAllDepartments(参数是顶级部门的集合);
public static List<Department> getAllDepartments(List<Department> list) { // 创建一个新的集合 List<Department> arrayList = new ArrayList<Department>(); //调用TreeDepartment方法 TreeDepartment(list, "├", arrayList); return arrayList; }
public static void TreeDepartment(Collection<Department> Toplist , String perfex ,List<Department> newList){ for (Department dep : Toplist) { Department copyDep = new Department(); copyDep.setId(dep.getId()); copyDep.setName(perfex+dep.getName()); newList.add(copyDep); TreeDepartment(dep.getChildren(), " "+perfex, newList); } } TreeDepartment方法: 首先把传过来的list集合遍历 根据遍历创建一个新的Department对象,用来接收拼接的department对象的name值 把这个对象添加到之前new的ArrayList集合中 再获取到当前对象的Children值(子部门),再调用本身 当当前department对象没有子部门的时候,不满足当前方法参数所需要的条件,递归就会停止 这样运用递归的方法就能成功的对部门做更好的显示效果,看起来像是子部门在父部门下面