Spring Boot Data — MongoDB
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.
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.
Create an Application Class
Create SpringbootDataMongodbApplication class as shown below. Using CommandLineRunner we will first save few records and then later fetch those records.
When you run your application, you should see output similar to the following:
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.
Conclusion:
If you would like to refer to the full code, do check my GitHub
Please do refer my other articles on Spring boot.