【发布时间】: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