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

40,273

Solution 1

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.

Solution 2

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

Solution 3

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

Share:
40,273
davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java & Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on December 25, 2021

Comments

  • davioooh
    davioooh over 2 years

    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?