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?
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.
You can use RelMongo framework which allows to implement relations by providing @OneToMany and @OneToOne annotations support.
If your relation is not based on dbref
, you can use @DocumentReference
https://spring.io/blog/2021/11/29/spring-data-mongodb-relation-modelling
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With