This article would demo how to use SpringBoot 2 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:
It’s very simple:
- the @Id indicates that the id is the MongoDB’s primary key
- the @Indexed means the code column would be indexed and keep unique
3.3 Define your MongoRepository
We should define a custom class which extends the MongoRepository to get the abilities of spring data mongodb.
The MongoRepository<Customer, Long> means:
- Our MongoDB document class is an instance of Customer
- Our MongoDB document id is an instance of Long
The parent class MongoRepository has many good features that you can use:
3.4 Configure by application.properties
3.5 Write a CommandLineRunner to test your code
Run the SpringBoot app and we would get this result:
You can see that spring data mongodb make the mongodb operations more simpler.