- 建立数据模型SysDept
- 创建数据库表
- 建立树形结构工具类
- 测试
递归生成一个树状json ,需要提供一个数据模型Sys Dept和建立树形结构的TreeNodeUtils。
- 首先获取所有节点的父节点。
- 递归创建父节点下的子节点树,并拼接。
- 递归子节点建立次子节点并拼接上,直至末端。
public class SysDept {
private Long deptId;
private Long parentId;
private String deptName;
// 子节点
private List children;
}
创建数据库表
create table `ry-vue`.sys_dept
(
dept_id bigint auto_increment comment '部门id'
primary key,
parent_id bigint default 0 null comment '父部门id',
ancestors varchar(50) default '' null comment '祖级列表',
dept_name varchar(30) default '' null comment '部门名称',
order_num int(4) default 0 null comment '显示顺序',
leader varchar(20) null comment '负责人',
phone varchar(11) null comment '联系电话',
email varchar(50) null comment '邮箱',
status char default '0' null comment '部门状态(0正常 1停用)',
del_flag char default '0' null comment '删除标志(0代表存在 2代表删除)',
create_by varchar(64) default '' null comment '创建者',
create_time datetime null comment '创建时间',
update_by varchar(64) default '' null comment '更新者',
update_time datetime null comment '更新时间'
)
comment '部门表' engine = InnoDB;
建立树形结构工具类
import com.example.demo.model.SysDept;
import java.util.ArrayList;
import java.util.List;
public class TreeNode {
// 建立父节点树形结构
public List buildTree(List depts){
ArrayList sysDepts = new ArrayList<>();
for (SysDept sysDept : getNodeTree(depts)) {
getChildrenNode(depts, sysDept);
sysDepts.add(sysDept);
}
return sysDepts;
}
// 查询所有的父节点,getParent()=0
private List getNodeTree(List depts){
ArrayList sysDepts = new ArrayList<>();
for (SysDept dept : depts) {
if (dept.getParentId()==0){
sysDepts.add(dept);
}
}
return sysDepts;
}
// 递归建立树形子节点,将子节点放到父节点下
private SysDept getChildrenNode(List depts,SysDept sysDept){
ArrayList sysDepts = new ArrayList<>();
for (SysDept dept : depts) {
if (dept.getParentId().equals(sysDept.getDeptId())){
sysDepts.add(getChildrenNode(depts,dept));
}
}
sysDept.setChildren(sysDepts);
return sysDept;
}
}
测试
import com.example.demo.mapper.SysDeptMapper;
import com.example.demo.model.SysDept;
import com.example.demo.node.TreeNode;
import net.minidev.json.JSONArray;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringNodeApplicationTests {
@Autowired
private SysDeptMapper sysDeptMapper;
@Test
void contextLoads() {
List sysDepts = sysDeptMapper.selectSysDept();
TreeNode treeNode = new TreeNode();
List sysDepts1 = treeNode.buildTree(sysDepts);
String s = JSONArray.toJSONString(sysDepts1);
System.out.println(s);
}
}



