【问题标题】:Morphia/MongoDB: Accessing "embedding" object from an @Embedded objectMorphia/MongoDB:从@Embedded 对象访问“嵌入”对象
【发布时间】:2012-01-16 18:48:19
【问题描述】:

我有一个类似于这个的 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(); 

【问题讨论】:

    标签: mongodb morphia


    【解决方案1】:

    既然您已经有了博客条目对象,为什么不使用一个简单的 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;
        }
    
    }
    

    【讨论】:

    • 感谢您的回复。我考虑循环浏览 BlogComments,但这似乎会很慢。我考虑的另一种可能性是向 BlogComment 添加一个字段“blogEntryId”,其中包含父对象的 id。这可能会更快,但在每个嵌入对象中显式存储嵌入对象的 ID 似乎并不正确。父级没有隐式句柄吗?
    • 循环遍历列表是内存中的操作,应该比从数据库中获取任何内容要快得多,因为后者涉及进程间通信、磁盘 IO(可能因为缓存而被放弃) 等。另一件事是你不能让 morphia 查询只返回一个嵌入的对象
    • 嗯,好的,很好地调用内存与数据库访问。是的,似乎 Morphia 查询即使使用“点表示法”也只会返回父对象而不是嵌入对象。使用循环似乎是要走的路,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多