问题
I have a Morphia schema similar to this one:
@Entity
class BlogEntry {
@Embedded
List<BlogComment> comments
}
@Embedded
class BlogComment {
String content
Long authorId
}
(code above just for illustration)
I'm trying to get a specific BlogComment in order to update it with new content. I have the corresponding BlogEntry object available, and I have the authorId, which let's say for the purposes of this question that these two together are sufficient to uniquely identify the correct BlogComment.
My question is, BlogComment does not explicitly contain a reference to its "parent" BlogEntry object, so how can I write a morphia query to retrieve this BlogComment? Something like:
//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();
回答1:
Since you already have the blog entry object why not use a simple Java loop to filter it out?
@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;
}
}
来源:https://stackoverflow.com/questions/8884813/morphia-mongodb-accessing-embedding-object-from-an-embedded-object