2

我有一个类似于这个的 Morphia 模式:

@Entity
class BlogEntry {
    @Embedded
    List<BlogComment> comments
}

@Embedded
class BlogComment {
    String content
    Long authorId
}

(上面的代码只是为了说明)

我正在尝试获取特定的 BlogComment 以便使用新内容对其进行更新。我有相应的 BlogEntry 对象可用,并且我有 authorId,假设出于这个问题的目的,这两个一起足以唯一标识正确的 BlogComment。

我的问题是,BlogComment 没有明确包含对其“父”BlogEntry 对象的引用,那么如何编写 morphia 查询来检索此 BlogComment?就像是:

//fetch the unique comment corresponding to this blog entry and this author ID.
BlogComment comment = ds.find(BlogComment.class, "blogEntryId =", blogEntry.id)
                        .filter("authorId", authorId)
                        .get(); 
4

1 回答 1

3

既然您已经有了博客条目对象,为什么不使用简单的 Java 循环将其过滤掉呢?

@Entity
class BlogEntry {

    @Embedded
    List<BlogComment> comments

    public BlogComment findCommentByAuthorId(String authorId) {
        if (null == authorId) return null;
        for (BlogComment comment: blogEntry.comments) {
           if (authorId.equals(comment.authorId) return comment;
        }
        return null;
    }

}
于 2012-01-17T23:08:53.497 回答