【问题标题】:When is @OneToMany list populated in Play framework?什么时候在 Play 框架中填充 @OneToMany 列表?
【发布时间】: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


    【解决方案1】:

    您希望调用 em.refresh(p) 而不是清除整个持久性上下文并分离所有其他实体。

    但这确实涉及查询数据库,因此 Play 稍后会在教程中实现一个辅助方法,该方法将在持久保存新评论后更新内存中的实体以节省您的旅行。

    【讨论】:

      【解决方案2】:

      在 JPA 中使用双向关系时,是否在内存中对象的关系双方之间保持一致性取决于您。

      我不确定 Play Framework 如何实现 find(),但如果 frontPostp 是同一实例(即不是从数据库数据构造的新实例),那么 comments 集合肯定是空的。

      【讨论】:

      • 谢谢,我了解到我需要使用 JPA.em().clear() 来清除 Hibernate 缓存并强制从数据库中检索对象。
      猜你喜欢
      • 1970-01-01
      • 2013-08-28
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      相关资源
      最近更新 更多