1

我的目标是使用带有 JPA 注释的 Hibernate OGM(4.1.1 Final)在存储 MongoDB 上保留一棵树。我编写了两个名为 Node 和 NodeLink 的类:第一个定义节点,第二个定义它们之间的链接。

节点类:

@Entity
public class Node {

private Set<NodeLink> children;

private String id;
private String name;

public Node() {
    children = new HashSet<>();
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

@OneToMany( mappedBy="source" )
public Set<NodeLink> getChildren() {
    return children;
}
void setChildren(Set<NodeLink> children) {
    this.children = children;
}

}

NodeLink 类:

@Entity
public class NodeLink {

private String id;

private Node source;
private Node target;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}

@ManyToOne
public Node getSource() {
    return source;
}
void setSource(Node source) {
    this.source = source;
}
public void assignSource(Node source) {
    setSource(source);
    source.getChildren().add(this);
}

@ManyToOne
public Node getTarget() {
    return target;
}
void setTarget(Node target) {
    this.target = target;
}
public void assignTarget(Node target) {
    setTarget(target);
}

}

创建类并持久化它们的代码如下:

    EntityTransaction transaction1 = manager.getTransaction();
    transaction1.begin();

    Node root = new Node();
    root.setName("root");
    Node children1 = new Node();
    children1.setName("children1");
    Node children2 = new Node();
    children2.setName("children2");

    NodeLink nl1 = new NodeLink();
    nl1.assignSource(root);
    nl1.assignTarget(children1);

    NodeLink nl2 = new NodeLink();
    nl2.assignSource(root);
    nl2.assignTarget(children2);

    manager.persist(root);
    manager.persist(children1);
    manager.persist(children2);
    manager.persist(nl1);
    manager.persist(nl2);

    transaction1.commit();

MongoDB中坚持的就是这个。

从图像中可以看出,“根”节点被正确地保留,并具有对子节点的正确引用。相反,“children1”和“children2”节点每个都有一个对 NodeLink 对象的引用,即使原始对象没有它们。所以我的问题是:这种行为是由于 Hibernate OGM 或 MongoDB 中的错误造成的?否则我的代码有错误?

4

1 回答 1

1

我想你发现了一个错误。我创建了一个问题并发送了一个拉取请求:https ://hibernate.atlassian.net/browse/OGM-1198

您可以尝试测试拉取请求或等到下一个版本。谢谢

于 2016-10-31T10:26:46.403 回答