Spring Boot Data — MongoDB

Mahesh Bonagiri
Towards Dev
Published in
3 min readDec 24, 2021

--

In Previous post I explained how to get started with Spring boot Data JPA. In this post we will discuss how to use Mongo DB with Spring Data.

Let’s start:

we will use Spring Initializer generate the base for our project, in my previous post I have explained how to get starting with Spring Boot + Eclipse.

Click ADD DEPENDENCIES and select Spring Data MongoDB, and Lombok. Generate and import into your favorite IDE. Eclipse will automatically download all required dependencies once imported.

The generated pom.xml file should look like below.

Define a Simple Entity

Lets create an Entity called BookEntity as shown below.

BookEntity.java

Here we have a BookEntity class with four attributes id, name, author and price. The constructor is used to create instances of Book Entities to be saved to the database. The class is annotated with @Document (marks BookEntity as domain object to be saved to DB), @Getter/@Setter (Lombok annotations) removes boilerplate code, @ToString method print outs the object’s properties. If the value of the @Id field is not null, it’s stored in the database as-is; otherwise, the converter will assume we want to store an ObjectId in the database

Repository Interface:

The Repository represents the DAO layer, which typically does all the database operations. Thanks to Spring Data, who provides the implementations for these methods.

Let’s have a look at our BookRepoisitory, which extends the MongoRepository, By extending MongoRepository, BookRepository inherits several methods for working with BookEntity persistence, including methods for saving, deleting, and finding Book entities.

Spring Data also lets you define other query methods by declaring their method signature. For example, BookRepository includes the findByAuthor() method.

BookRepository.java

Create an Application Class

Create SpringbootDataMongodbApplication class as shown below. Using CommandLineRunner we will first save few records and then later fetch those records.

Spring Boot Data MongoDB Application

When you run your application, you should see output similar to the following:

Spring Data MongoDB log

Bonus Point:

As you can observe Spring boot created above collection with our Entity name called BookEntity, we can change that by updating @Document annotation with (collection = “books”). This will create collection with books instead of BookEntity as shown below.

With Collection name books

Conclusion:

If you would like to refer to the full code, do check my GitHub

Please do refer my other articles on Spring boot.

--

--