-SpringBoot 2 and mongodb CRUD example using MongoRepository
This article would demo how to use SpringBoot’s mongotemplate to do simple CRUD(create-read-update-delete) operations on MongoDB.
- SpringBoot 2.x
- 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.4 Configure by application.properties
3.5 Write a CommandLineRunner to test your code
You can see that spring data mongotemplate makes the mongodb operations more simpler.