部门树形结构 全部查询

  • Post author:
  • Post category:其他




表结构

CREATE TABLE `dept` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) DEFAULT NULL,
  `pid` int(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;



数据

INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (1, '部门1', 0);
INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (2, '部门2', 0);
INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (3, '部门3', 0);
INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (4, '部门4', 1);
INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (5, '部门5', 1);
INSERT INTO `dev_help`.`dept`(`id`, `dept_name`, `pid`) VALUES (6, '部门6', 4);



java 实体

@Data
public class Dept implements Serializable {
    
    private Integer id;
    
    private String deptName;
    
    private Integer pid;
    
    private List<Dept> list;
}



递归查询所以部门

/*
  查询所以部门
*/
 public List<Dept > getTree(){
 // 先查询一级部门
 List<Dept > dept= deptMapper.queryDeptByPid("0");
        ArrayList<Dept> tree = new ArrayList<>();
        dept.forEach(d-> {
            List<Dept > treeList = deptMapper.deptMapper(d.getId());
            // 递归查询自己的所以子集
            getChildren(treeList );
            d.setList(treeList );
            tree.add(catalogueTreeDTO);
        });
        return tree;
    }
	/**
     * 递归查询
     * @param list
     */
  public void getChildren(List<Dept> list){
        List<Dept > retList = new ArrayList<>();
        for (Dept dept: list) {
            retList = deptMapper.queryDeptByPid(dept.getId());
            if(retList.size() > 0){
                // 循环自己调自己
                dept.setList(retList);
                getChildren(retList);
            }
        }
    }



版权声明:本文为weixin_47748260原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。