Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll look at Spring Data MongoDB's @DBRef annotation. We'll connect MongoDB documents using this annotation. Additionally, we’ll see the types of MongoDB database references and compare them as well.

2. MongoDB Manual Database Reference

The first type that we discuss is called the manual reference. In MongoDB, every document must have an id field. Therefore, we can rely on using it and connect documents with it.

When using manual references, we store the _id of the referenced document in another document. 

Later on, when we are querying data from the first collection, we can start a second query to fetch the referenced documents.

3. Spring Data MongoDB @DBRef Annotation

DBRefs are similar to manual references in the sense that they also contain the referenced document’s _id. However, they contain the referenced document’s collection in the $ref field and optionally its database as well in the $db field.

The advantage of this over manual references is that it clarifies which collection we are referencing.

4. Application Setup

4.1. Dependency

Firstly, we need to add the required dependencies to use MongoDB with Spring Boot.

Let’s add spring-boot-starter-data-mongodb to our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

4.2. Configuration

Now, we set up the connection by adding the following configuration to the application.properties file:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=person_database

Let’s run the application to test whether we can connect to the database. We should see a message similar to this in the logs:

Opened connection [connectionId{localValue:2, serverValue:37}] to localhost:27017

This means that the application could successfully connect to MongoDB.

4.3. Collections

In MongoDB, we use collections to store individual documents. They are the counterpart of tables in relational databases.

In this example, we'll work with three different data types: Person, Dog, and Cat. We’ll connect persons to their pets.

Let’s create the collections in the database with some data. We can use Mongo Express for this, but any other tool would work as well.

Firstly, let’s create a database named person_database and create two collections inside it named Dog and Cat. We'll insert one document into each one. To simplify, both of them will have only one property: the pet's name.

Let’s insert this document into the Dog collection:

{
    _id: ObjectID("622112d71f9dac417b84227d"), 
    name: "Max"
}

Then, let's insert this document into the Cat collection:

{
    _id: ObjectID("622112781f9dac417b84227b"),
    name: "Loki"
}

Now, let’s create the Person collection and insert a document into it:

{
    _id: ObjectId(),
    name: "Bob",
    pets: [
        {
          "$ref": "Cat",
          "$id": "622112781f9dac417b84227b",
          "$db": ""
        },    
        {
          "$ref": "Dog",
          "$id": "622112d71f9dac417b84227d",
          "$db": ""
        }
    ]
}

We provide the pets as an array. The items of the array need to follow a specific format to be able to use them as DBRefs. We need to provide the name of the collection in the $ref property. In this case, it's Cat and Dog. Then, we include the ID of the referenced documents. Lastly, we can optionally include a database name in the $db property if we would like to reference the collections from a different database.

5. Using the @DBRef Annotation

We can map the previously created collections to Java classes, similar to what we would do when working with a relational database.

To simplify, we won’t create separate classes for the Dog and Cat data types. Instead, we’ll use a Pet class that contains an ID and a name:

public class Pet {
    private String id;
    private String name;

    @Override 
    public String toString() {
        return "Pet [id=" + id + ", name=" + name + "]";
    }

    // standard getters and setters
}

Now, we’ll create the Person class and include an association to the Pet class via @DBRef:

@Document(collection = "Person")
public class Person {

    @Id
    private String id;
    
    private String name;

    @DBRef
    private List<Pet> pets;

    @Override 
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", pets=" + pets + "]";
    }

    // standard getters and setters
}

Next, let’s create a simple repository to be able to query data:

public interface PersonRepository extends MongoRepository<Person, String> {}

We'll test everything by creating an ApplicationRunner that executes a MongoDB query when we start the application. Let's override the run() method and put a log statement so we can see the contents of the Person collection:

@Override
public void run(ApplicationArguments args) throws Exception {
    logger.info("{}", personRepository.findAll());
}

This produces a log output similar to this because we have overridden the toString() method in our entity classes:

com.baeldung.mongodb.dbref.DbRefTester : [Person [id=62249c5c7ffe83c50ad12700, name=Bob, pets=[Pet [id=622112781f9dac417b84227b, name=Loki], Pet [id=622112d71f9dac417b84227d, name=Max]]]]

This means that we successfully read and joined documents from different collections.

5.1. Reference a Different Database

The @DBRef annotation accepts two parameters. One of them is the db parameter, which can be used to reference documents in other databases.

This is optional, which means that the application looks for referenced documents in the same database if we don't provide this value.

In our case, if the Cat or Dog would reside in a different database named pet_database, we would need to change the annotation to this: @DBRef(db = “pet_database”).

5.2. Lazy Loading

The other parameter accepted by the annotation is called lazy. This is a boolean value that determines if the referenced documents should be loaded lazily or not.

By default, it is false, which means that the references will be loaded eagerly when we query the main entity. If we turn this feature on, the referenced documents will not be loaded until they are accessed first.

6. Conclusion

In this article, we compared MongoDB manual references with Spring Data MongoDB @DBRef. We created three collections and connected them with this annotation. We created a Spring Boot application to query these collections using a MongoRepository and displayed the related documents.

As always, the source code for the examples is available over on GitHub.

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!