Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB: how to implement "entity relationships"?

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 entities in application model classes working with MongoDB.

Working with JPA I often use @ManyToMany or @OneToMany annotations to define relationships between objects. Is there something similar in Spring Data MongoDB?

Studying MongoDB I realized that there are two possible approaches to the association: References and Embedded Data.

Which one is used by Spring Data? Is it possible to configure the association mode?

like image 684
davioooh Avatar asked Mar 27 '15 15:03

davioooh


3 Answers

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.

From spring data documentation

@DBRef - applied at the field to indicate it is to be stored using a 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.

like image 158
Ignacio A. Poletti Avatar answered Nov 19 '22 22:11

Ignacio A. Poletti


You can use RelMongo framework which allows to implement relations by providing @OneToMany and @OneToOne annotations support.

like image 44
Ledher bay Avatar answered Nov 19 '22 22:11

Ledher bay


If your relation is not based on dbref, you can use @DocumentReference https://spring.io/blog/2021/11/29/spring-data-mongodb-relation-modelling

like image 1
Hett Avatar answered Nov 19 '22 21:11

Hett