数据模型:
我在 neo4j 中存储了一个树结构,其中 :Node
类型的节点可以是相同类型节点的父节点。
:Node
右侧显示的节点。树的根(显示为红色)与叶子共享一些属性,因此有一个名为 AbstractNode
的抽象类:
public abstract class AbstractNode {
private Long id;
@NotEmpty
private String code;
@Relationship(type = "SUBTREE_OF", direction = Relationship.INCOMING)
private Set<Node> children;
<getters & setters omitted>
}
父节点的类:
public class CodeSet extends AbstractNode {
@Relationship(type = "SUBTREE_OF", direction = Relationship.OUTGOING)
private Application parent;
<getters and setters omitted>
}
子节点的类:
public class Node extends AbstractNode {
@NotEmpty
private String description;
@NotEmpty
private String type;
@NotEmpty
private String name;
@NotNull
@Relationship(type = "SUBTREE_OF", direction = Relationship.OUTGOING)
private AbstractNode parent;
<getters and setters omitted>
}
服务层:
此方法用于检索指定深度的节点信息:
@Transactional(readOnly = true)
public Node findById(Long id, int depth) throws EntityNotFoundException {
Node entity = nodeRepository.findOne(id, depth);
if (entity == null) {
throw new EntityNotFoundException(String.format("Node %d not found", id));
} else {
return entity;
}
}
问题:
当获取 :Node
节点时,具有相同类型父节点的节点在子节点列表中有这些父节点,这显然是错误的并导致其他问题。请参阅所描述数据集的调试器屏幕截图:
如何解决?
最佳答案
使用 Spring Data Neo4j (SDN),当存在相同类型的传入和传出关系的组合时,您需要同时注释传入关系字段的字段和 setter/getter,否则最终会得到不正确的映射。
这是在 SDN documentation 中说的:
The direction attribute on a @Relationship defaults to OUTGOING. Any fields or methods backed by an INCOMING relationship must be explicitly annotated with an INCOMING direction.
在 neo4j-ogm 中还创建了一个问题/功能请求(spring data neo4j 4+中使用的映射库)关于这个。
关于java - 如何避免 spring data neo4j 获取父节点作为树数据结构中子集合的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294772/