springboot树形结构实例
时间: 2023-07-27 22:21:19 浏览: 111
下面是一个基于Spring Boot实现树形结构的示例,其中使用了Mybatis-Plus作为ORM框架和MySQL作为数据库:
首先创建一个名为`tree_node`的MySQL表,用于存储树形节点的数据:
```sql
CREATE TABLE `tree_node` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '节点ID',
`parent_id` bigint(20) DEFAULT NULL COMMENT '父节点ID',
`name` varchar(255) NOT NULL COMMENT '节点名称',
PRIMARY KEY (`id`),
KEY `idx_parent_id` (`parent_id`),
CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `tree_node` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='树形节点表';
```
然后创建一个名为`TreeNode`的实体类,对应上述数据库表的结构:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tree_node")
public class TreeNode {
@TableId(type = IdType.AUTO)
private Long id;
@TableField(value = "parent_id")
private Long parentId;
private String name;
@TableField(exist = false)
private List<TreeNode> children;
}
```
接下来创建一个名为`TreeService`的服务类,用于处理树形结构相关操作:
```java
@Service
public class TreeService {
@Autowired
private TreeNodeMapper treeNodeMapper;
// 获取树形结构
public List<TreeNode> getTree() {
List<TreeNode> roots = treeNodeMapper.selectList(new QueryWrapper<TreeNode>().isNull("parent_id"));
for (TreeNode root : roots) {
root.setChildren(getChildren(root.getId()));
}
return roots;
}
// 获取指定节点的子节点
private List<TreeNode> getChildren(Long parentId) {
List<TreeNode> children = treeNodeMapper.selectList(new QueryWrapper<TreeNode>().eq("parent_id", parentId));
for (TreeNode child : children) {
child.setChildren(getChildren(child.getId()));
}
return children;
}
// 添加节点
public void addNode(TreeNode node) {
treeNodeMapper.insert(node);
}
// 删除节点及其子节点
public void deleteNode(Long nodeId) {
treeNodeMapper.deleteById(nodeId);
treeNodeMapper.delete(new QueryWrapper<TreeNode>().eq("parent_id", nodeId));
}
}
```
其中`TreeNodeMapper`是Mybatis-Plus生成的Mapper接口,用于操作数据库表。
最后创建一个名为`TreeController`的控制器,用于处理HTTP请求:
```java
@RestController
@RequestMapping("/tree")
public class TreeController {
@Autowired
private TreeService treeService;
// 获取树形结构
@GetMapping("/get")
public List<TreeNode> getTree() {
return treeService.getTree();
}
// 添加节点
@PostMapping("/add")
public void addNode(@RequestBody TreeNode node) {
treeService.addNode(node);
}
// 删除节点
@DeleteMapping("/delete/{id}")
public void deleteNode(@PathVariable Long id) {
treeService.deleteNode(id);
}
}
```
以上示例仅供参考,具体实现方式可以根据实际需求进行调整。
阅读全文