【问题标题】:Tree with JPA[/Hibernate]使用 JPA 的树[/Hibernate]
【发布时间】:2011-02-25 12:59:02
【问题描述】:

Grrrrrr,试图实现一个非常简单的树。它不需要是双向的(因为遍历只是自上而下),所以我认为如果它是单向的会更好(即更节省空间),尽管我的映射失败了:

@Entity
public class Node extends Model {

    @Column(nullable=false, unique=true)
    public String description;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    public List<Node> children = new LinkedList<Node>();

    public Node() {}
    public Node(String description) {
        this.description = description;
    }

    public void addChild(String description) {

        Node child = new Node(description);
        child.save();

        this.children.add(child);
    }
}

“失败”是指子关系没有被映射,以下单元测试失败;最后一个 assert 期望 1 但得到 0。在应用程序的 CRUD 部分中,我可以看到两个节点实际上都已创建并持久化,但父节点没有任何子节点。由此我得出结论,映射已损坏:

public void testMenu() {

    Node root = Node.find("byDescription", "root").first();
    if (root == null) {
        root = new Node("root");
        root.save();
    }

    assertNotNull(root);

    root.addChild("child 1");

    JPA.em().flush();
    JPA.em().getTransaction().commit();
    JPA.em().getTransaction().begin();
    JPA.em().clear(); // clear cache to grab the root from the db

    root = Node.find("byDescription", "root").first();
    assertEquals(1, root.children.size());

}

我正在使用 Play!,这就是为什么所有这些成员都是公共的而不是私有的,为什么没有 getter/setter,以及为什么没有 Id 字段(Id 是从 Model 类继承的)。这也是为什么那里有一些看起来不标准的函数,比如find()save()。它们的功能非常直观,对公共成员的访问通过反射“转换”为调用提供或创建的 setter 和 getter。

这没关系,是我的映射被破坏了,所以请尝试并专注于这个问题,而不是其他问题,我很确定这不是问题的根源。

干杯。

更新:

休眠日志:

Hibernate: /* from models.Node where description = ? */ select node0_.id as id35_, node0_.description as descript2_35_ from Node node0_ where node0_.description=? limit ?
Hibernate: /* insert models.Node */ insert into Node (description) values (?)
Hibernate: /* insert models.Node */ insert into Node (description) values (?)
Hibernate: /* from models.Node where description = ? */ select node0_.id as id35_, node0_.description as descript2_35_ from Node node0_ where node0_.description=? limit ?
Hibernate: /* load collection models.Node.children */ select children0_.Node_id as Node1_35_1_, children0_.children_id as children2_1_, node1_.id as id35_0_, node1_.description as descript2_35_0_ from Node_Node children0_ inner join Node node1_ on children0_.children_id=node1_.id where children0_.Node_id=?

【问题讨论】:

    标签: java hibernate jpa tree playframework


    【解决方案1】:

    如果您粘贴休眠日志会有所帮助。

    这不是绝对必要的,但您可以在 root.addChild("child 1"); 之后尝试 root.save();

    此外,您没有提交事务,如果 Node.find() 使用相同的会话,那不会有问题,但会吗?

    【讨论】:

    • 我已经尝试重新排序所有创建/保存/刷新/持久操作。没有帮助。我现在将添加 Hibernate 日志。
    • 顺便问一下,您使用的是哪个版本的 JPA? JPA 1.0 不支持 onetomany 单向
    • 使用 JPA 2.0,休眠 3.5.6。 $hit,等等,也许我还没有尝试过这个命令,因为直到现在root.save() 是在一个单独的方法中
    • 我确定有一个组合错过了;)
    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2014-01-16
    相关资源
    最近更新 更多