Java Spring Data MongoDB:如何实现“实体关系”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29303916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data MongoDB: how to implement "entity relationships"?
提问by davioooh
The title of this question is quite contradictory since I'm trying to implement relations in a non-relational database... :)
这个问题的标题很矛盾,因为我试图在非关系数据库中实现关系...... :)
But what I mean is how to define associations between entitiesin application model classes working with MongoDB.
但我的意思是如何在使用 MongoDB 的应用程序模型类中定义实体之间的关联。
Working with JPA I often use @ManyToMany
or @OneToMany
annotations to define relationships between objects. Is there something similar in Spring Data MongoDB?
与JPA我经常工作使用@ManyToMany
或@OneToMany
注解来定义对象之间的关系。Spring Data MongoDB 中有类似的东西吗?
Studying MongoDB I realized that there are two possible approaches to the association: Referencesand Embedded Data.
学习 MongoDB 我意识到有两种可能的关联方法:References和Embedded Data。
Which one is used by Spring Data? Is it possible to configure the association mode?
Spring Data 使用哪一个?是否可以配置关联模式?
采纳答案by Ignacio A. Poletti
You can use the @DBRef annotation to persist the referenced class in a separate collection, else the document will be persisted in the same document (json). The use of DBRef require an extra query for the mongodb driver, you should consider this to analyze performance issues.
您可以使用 @DBRef 批注将引用的类持久化到单独的集合中,否则文档将持久化在同一个文档 (json) 中。使用 DBRef 需要额外查询 mongodb 驱动程序,您应该考虑这一点来分析性能问题。
From spring data documentation
来自弹簧数据文档
@DBRef - applied at the field to indicate it is to be stored using a com.mongodb.DBRef.
@DBRef - 应用于该字段以指示它将使用 com.mongodb.DBRef 存储。
7.3.4 Using DBRefs The mapping framework doesn't have to store child objects embedded within the document. You can also store them separately and use a DBRef to refer to that document. When the object is loaded from MongoDB, those references will be eagerly resolved and you will get back a mapped object that looks the same as if it had been stored embedded within your master document.
7.3.4 使用 DBRefs 映射框架不必存储嵌入在文档中的子对象。您还可以单独存储它们并使用 DBRef 来引用该文档。当对象从 MongoDB 加载时,这些引用将被急切地解析,您将返回一个映射对象,该对象看起来与嵌入在主文档中的存储相同。