How to rebuild a tree from PostgreSQL without duplicate nodes? Closed
asked 1 month ago by @qa-y3w2o1znmdumvx0dhfwl 0 rep · 69 views
I'm developing a Spring Boot application that stores a tree structure in PostgreSQL.
The table schema is:
CREATE TABLE nodes (
id BIGINT PRIMARY KEY,
value VARCHAR(150),
parent_id BIGINT
);
Example data:
1 | Management | NULL
2 | IT Department | 1
3 | Developer | 2
To rebuild the tree in memory, I'm using Java Collections:
private final Map<Long, List<Long>> tree = new HashMap<>();
public void loadTree(List<NodeEntity> nodes) {
for (NodeEntity node : nodes) {
if (node.getParentId() != null) {
tree.putIfAbsent(node.getParentId(), new ArrayList<>());
tree.get(node.getParentId()).add(node.getId());
}
}
}
The problem is that after reloading the data several times, some child nodes appear duplicated in the generated tree structure.
Observed behavior:
Management
├─ IT Department
│ ├─ Developer
│ └─ Developer
Expected behavior:
Management
└─ IT Department
└─ Developer
I suspect that the in-memory collections should be cleared before rebuilding the tree, but I'm not sure if that's considered the best approach.
What is the recommended way to rebuild a hierarchical tree structure from database records without introducing duplicate nodes?