Morphia/MongoDB:访问“嵌入" @Embedded对象中的对象 [英] Morphia/MongoDB: Accessing "embedding" object from an @Embedded object

查看:158
本文介绍了Morphia/MongoDB:访问“嵌入" @Embedded对象中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此相似的Morphia模式:

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)

我正在尝试获取特定的BlogComment以便用新内容对其进行更新.我有相应的BlogEntry对象,还有authorId,就这个问题而言,这两个对象足以唯一地标识正确的BlogComment.

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.

我的问题是,BlogComment没有显式包含对其父" BlogEntry对象的引用,那么我该如何编写一个词素查询来检索此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(); 

推荐答案

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

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;
    }

}

这篇关于Morphia/MongoDB:访问“嵌入" @Embedded对象中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆