eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments