springboot树形结构示例
时间: 2023-06-30 16:21:32 浏览: 53
下面是一个使用Spring Boot实现树形结构的示例:
首先,定义一个实体类Node,表示树节点:
```
public class Node {
private int id;
private String name;
private int parentId;
private List<Node> children = new ArrayList<>();
// getter and setter
}
```
接着,定义一个服务类NodeService,提供获取树节点列表、构建树等功能:
```
@Service
public class NodeService {
@Autowired
private NodeMapper nodeMapper;
public List<Node> getAllNodes() {
return nodeMapper.getAllNodes();
}
public Node buildTree(List<Node> nodes) {
Map<Integer, Node> nodeMap = new HashMap<>();
nodes.forEach(node -> nodeMap.put(node.getId(), node));
Node root = null;
for (Node node : nodes) {
if (node.getParentId() == 0) {
root = node;
} else {
Node parent = nodeMap.get(node.getParentId());
if (parent != null) {
parent.getChildren().add(node);
}
}
}
return root;
}
}
```
其中,NodeMapper是一个MyBatis的Mapper接口,用于从数据库中获取树节点列表。
最后,在Controller中调用NodeService获取树节点列表,并构建树:
```
@RestController
public class NodeController {
@Autowired
private NodeService nodeService;
@GetMapping("/nodes")
public Node getNodes() {
List<Node> nodes = nodeService.getAllNodes();
return nodeService.buildTree(nodes);
}
}
```
这样,当访问“/nodes”接口时,会返回树形结构的节点列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)