Morphia/MongoDB: Accessing “embedding” object from an @Embedded object

为君一笑 提交于 2020-01-04 05:54:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!