【发布时间】:2011-01-12 22:47:41
【问题描述】:
Play 框架的 Yet Another Blog Engine example 有一个带有子评论的 Post 类:
// Post.java
// ... other fields, etc.
@OneToMany(mappedBy="post", cascade=CascadeType.ALL)
public List<Comment> comments;
// ...
当数据由 .yml 填充时,一切似乎都正常:
// BasicTest.java
@Test
public void fullTest() {
Fixtures.load("data.yml");
// ...
// Find the most recent post
Post frontPost = Post.find("order by postedAt desc").first();
assertNotNull(frontPost);
// ...
// Check that this post has two comments
assertEquals(2, frontPost.comments.size()); // succeeds
}
但是当我手动将帖子和一些评论保存到数据库时,frontPost.cmets 字段为空:
@Test
public void myFullTest() {
// Fixtures.load("data.yml");
User u = new User("bob@gmail.com", "secret", "Bob").save();
Post p = new Post(u, "About the model layer", "The model has a central position in a Play! application. It is the ...").save();
Comment c1 = new Comment(p, "Guest", "You are right !").save();
Comment c2 = new Comment(p, "Mike", "I knew that ...").save();
// Find the most recent post
Post frontPost = Post.find("order by postedAt desc").first();
// This assertion fails as frontPost.comments is empty:
// "Failure, expected:<2> but was <0>"
assertEquals(2, frontPost.comments.size());
}
为什么会发生这种情况,如何让 JPA 在逐个保存类时填充 Post.cmets 字段?
谢谢大家!
更新:解决方案是在 find(....) 调用之前调用 JPA.em().clear()。
【问题讨论】:
标签: hibernate jpa playframework