[英]How to code the hierarchical relationship to the node of the same type properly in spring data neo4j?
我想使用Neo4j存储一个树数据结构。
有一个父节点:CodeSet
,它始终是树的根,还有一个子节点:Node
,它们本身可以具有相同类型的子节点。 它们通过以下类型的关系连接:SUBTREE_OF
:
父节点显示为红色,并且其本身有一个父节点显示为绿色。
一旦父节点和子节点有了一些通用数据,我就创建了一个抽象类:
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>
}
我需要的只是对子节点进行更新。 我在服务层使用以下方法:
public Node update(Node node, Long nodeId) throws EntityNotFoundException {
Node updated = findById(nodeId, 0);
updated.setDescription(node.getDescription());
updated.setType(node.getType());
updated.setName(node.getName());
updated.setCode(node.getCode());
nodeRepository.save(updated);
return updated;
}
有了这个我得到以下结果: 关系破裂了。 我还尝试在
findById
方法参数中指定depth=1
,但这又导致错误的关系:
之后,我尝试将类中的双向关系修改为单向性,这样只有一个类具有带@Relatinship
字段的注释,该注释指向另一个,但是这也无济于事。
如何使这项工作?
通过更新服务方法中的保存操作来解决:
public Node update(Node node, Long nodeId) throws EntityNotFoundException {
Node updated = findById(nodeId, 0);
updated.setDescription(node.getDescription());
updated.setType(node.getType());
updated.setName(node.getName());
updated.setCode(node.getCode());
//added param depth=0 here
nodeRepository.save(updated, 0);
return updated;
}
您在抽象类中对关系的定义可能存在问题。 子节点也继承INCOMING关系,因此当您使用深度1更新时,关系是双向的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.