的遊戲框架的Yet Another Blog Engine example有郵政類兒童點評:Play框架中填充@OneToMany列表的時候是什麼時候?
// 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
}
但是當我手動保存Post和一些評論到數據庫時,frontPost.comments字段爲空:
@Test
public void myFullTest() {
// Fixtures.load("data.yml");
User u = new User("[email protected]", "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.comments字段?
謝謝大家!
更新:解決方法是在find(....)調用之前調用JPA.em()。clear()。
謝謝,我瞭解到我需要使用JPA.em()。clear()來清除Hibernate緩存並強制從數據庫中檢索對象。 – tba 2011-01-13 00:05:12