java 实现用户部门的上级树结构
时间: 2024-01-22 20:03:14 浏览: 78
以树的方式展现用户之间的层级关系
假设您有以下表结构:
- 用户表 user(id, name, department_id)
- 部门表 department(id, name, parent_id)
其中,`department` 表的 `parent_id` 字段表示父级部门的 id,如果该字段为 `NULL`,则表示该部门为顶级部门。
现在,假设您已经获取了当前用户的 `id`,您可以使用以下 Java 代码查询该用户所在的部门树结构:
```java
import java.sql.*;
import java.util.*;
public class UserDepartmentTree {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(
"WITH RECURSIVE department_tree(id, name, parent_id, depth) AS (" +
" SELECT id, name, parent_id, 0" +
" FROM department" +
" WHERE id = (SELECT department_id FROM user WHERE id = ?)" +
" UNION ALL" +
" SELECT d.id, d.name, d.parent_id, dt.depth + 1" +
" FROM department d" +
" JOIN department_tree dt ON d.id = dt.parent_id" +
")" +
"SELECT id, name, parent_id, depth" +
" FROM department_tree" +
" ORDER BY depth")) {
stmt.setInt(1, 1); // 假设当前用户的 id 为 1
ResultSet rs = stmt.executeQuery();
// 构建部门树结构
Map<Integer, Department> map = new HashMap<>();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int parentId = rs.getInt("parent_id");
int depth = rs.getInt("depth");
Department department = new Department(id, name, parentId, depth);
map.put(id, department);
if (parentId != 0) {
map.get(parentId).addChild(department);
}
}
// 打印部门树结构
Department root = map.get(1); // 假设当前用户所在的部门为顶级部门
printDepartmentTree(root, 0);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void printDepartmentTree(Department root, int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.getName());
for (Department child : root.getChildren()) {
printDepartmentTree(child, level + 1);
}
}
private static class Department {
private int id;
private String name;
private int parentId;
private int depth;
private List<Department> children = new ArrayList<>();
public Department(int id, String name, int parentId, int depth) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.depth = depth;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getParentId() {
return parentId;
}
public int getDepth() {
return depth;
}
public List<Department> getChildren() {
return children;
}
public void addChild(Department child) {
children.add(child);
}
}
}
```
这里使用了递归查询语句(`WITH RECURSIVE`)查询部门树结构,并将查询结果转换为一个部门树结构,最终按照深度打印出部门树结构。
需要注意的是,上述代码中的 `1` 需要替换为当前用户的实际 `id` 值。同时,您需要根据您使用的数据库类型和 JDBC 驱动程序来执行 SQL 查询,并将查询结果转换为您所需的数据结构。
阅读全文