我有一个与此类似的 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();
最佳答案
既然您已经有了博客条目对象,为什么不使用简单的 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;
}
}
关于mongodb - Morphia/MongoDB : Accessing "embedding" object from an @Embedded object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884813/