-SpringBoot 2 and mongodb CRUD example using MongoRepository
1. Introduction
This article would demo how to use SpringBoot’s mongotemplate to do simple CRUD(create-read-update-delete) operations on MongoDB.
2. Environments
- SpringBoot 2.x
- MongoDB
- jdk 1.8
3. The example
3.1 Define dependency in your pom
Add spring data mongodb to your pom like this:
3.2 Define your domain class
Let’s define a domain class that would map to MongoDB document like this:
3.3 Define your MongoDB Config class
We should define a config class to access MongoDB.
It’s very simple:
- It’s a @Configuration class which indicates this class has some bean definitions.
- It extends the AbstractMongoConfiguration to extend and do some customizations on MongoDB configurations.
- It uses @Value annotation to read MongoDB configrations from application.properties
- The most important is that this class return a MongoTemplate class to be used to access MongoDB
3.5 Write a CommandLineRunner to test your code
4. Summary
You can see that spring data mongotemplate makes the mongodb operations more simpler.