java代码实现部门树以及任意树结构的获取

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5Lya55CG6LSi55qE56iL5bqP5ZGY5LiN5piv5aW9REo=,size_6,color_FFFFFF,t_70,g_se,x_16

 

 表结构如下:



SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for my_dept
-- ----------------------------
DROP TABLE IF EXISTS `my_dept`;
CREATE TABLE `my_dept`  (
  `dept_id` int NOT NULL AUTO_INCREMENT COMMENT 'id值',
  `parent_id` int NULL DEFAULT NULL COMMENT '上级部门',
  `dept_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
  `sort` int NULL DEFAULT NULL COMMENT '排序',
  `status` bit(1) NOT NULL COMMENT '状态',
  `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`dept_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of my_dept
-- ----------------------------
INSERT INTO `my_dept` VALUES (1, 0, '成都总公司', 1, b'1', '2022-01-30 11:01:09', '2022-01-30 18:21:26');
INSERT INTO `my_dept` VALUES (2, 1, '研发部门', 1, b'1', '2022-01-30 11:01:28', '2022-01-30 11:01:30');
INSERT INTO `my_dept` VALUES (3, 1, '市场部门', 2, b'1', '2022-01-30 11:01:47', '2022-01-30 11:01:48');
INSERT INTO `my_dept` VALUES (4, 1, '运维部门', 3, b'1', '2022-01-30 11:02:01', '2022-01-30 11:02:04');
INSERT INTO `my_dept` VALUES (5, 0, '宜宾分公司', 2, b'1', '2022-01-30 11:07:36', '2022-01-30 14:18:48');
INSERT INTO `my_dept` VALUES (6, 5, '营销部门', 1, b'1', '2022-01-30 11:08:40', '2022-01-30 20:32:40');
INSERT INTO `my_dept` VALUES (7, 5, '运维部门', 2, b'1', '2022-01-30 11:08:56', '2022-01-30 18:03:56');
INSERT INTO `my_dept` VALUES (8, 5, '公关部门', 3, b'1', '2022-01-30 20:47:32', '2022-01-30 20:47:29');

SET FOREIGN_KEY_CHECKS = 1;

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5Lya55CG6LSi55qE56iL5bqP5ZGY5LiN5piv5aW9REo=,size_15,color_FFFFFF,t_70,g_se,x_16

对应的实体类:

package com.chunwai.entity;

import com.baomidou.mybatisplus.annotation.IdType;

import java.util.ArrayList;
import java.util.Date;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * <p>
 *
 * </p>
 *
 * @author leungchunwai
 * @since 2022-01-30
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class MyDept implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id值
     */
    @TableId(value = "dept_id", type = IdType.AUTO)
    private Integer deptId;

    /**
     * 上级部门
     */
    private Integer parentId;

    /**
     * 名称
     */
    private String deptName;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 状态
     */
    private Boolean status;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;

    /**
     * 子级部门
     */
    @TableField(exist = false)
    private List<MyDept> children = new ArrayList<>();

}

 业务层逻辑:

package com.chunwai.service.impl;

import com.chunwai.entity.MyDept;
import com.chunwai.mapper.MyDeptMapper;
import com.chunwai.service.IMyDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.velocity.runtime.directive.Break;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author leungchunwai
 * @since 2022-01-30
 */
@Service
public class MyDeptServiceImpl extends ServiceImpl<MyDeptMapper, MyDept> implements IMyDeptService {

    @Override
    public List<MyDept> treeData() {
        List<MyDept> myDeptList = list();
        Map<Integer, MyDept> myDeptMap = myDeptList.stream()
                .collect(Collectors.toMap(MyDept::getDeptId, MyDept -> MyDept));
        List<MyDept> arrayList = new ArrayList<>();
        myDeptList.forEach(myDept -> {
            if (myDept.getParentId() == 0 ){
                arrayList.add(myDept);
            }else {
                MyDept dept = myDeptMap.get(myDept.getParentId());
                dept.getChildren().add(myDept);
            }
        });
        return arrayList;
    }
}

控制层调用返回给前端:

package com.chunwai.controller;


import com.chunwai.entity.CourseType;
import com.chunwai.entity.MyDept;
import com.chunwai.service.ICourseTypeService;
import com.chunwai.service.IMyDeptService;
import com.chunwai.utils.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author leungchunwai
 * @since 2022-01-30
 */
@RestController
@RequestMapping("/myDept")
@Api(tags = "部门树")
public class MyDeptController {
    @Autowired
    private IMyDeptService myDeptService;

    @GetMapping
    public AjaxResult treeData(){
        List<MyDept> treeData = myDeptService.treeData();
        return AjaxResult.me().setResultObj(treeData);

    }
}

返回结果如下:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5Lya55CG6LSi55qE56iL5bqP5ZGY5LiN5piv5aW9REo=,size_16,color_FFFFFF,t_70,g_se,x_16

 

 

 

  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
假设您有以下表结构: - 用户表 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 查询,并将查询结果转换为您所需的数据结构。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会理财的程序员不是好摄影师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值