Spring Boot POST Request with MongoDB
In this tutorial, I will describe how to create a Spring Boot POST Request using a MongoDB database. Let’s get started.
Setup
- IntelliJ IDEA 2019.3.3 as IDE
- JDK 11
- MongoDB as database
- MongoDB Compass as a mongoDB data visualize tool
- Postman as Rest API testing tool
Create a new Spring Boot Project
Open your favourite browser and go to https://start.spring.io/ .
Select Project as Maven, Language as Java, and here I used Spring Boot version 2.5.0 and Java version 11. Enter Project Name and add the following Dependencies.
Spring Boot DevTools, Lombok,Spring Web and Spring Data MongoDB
Now click GENERATE to download the spring Boot Project. Extract the zipped file and Open it with IntelliJ IDEA. Now the project structure will look like this.
Connect to mongoDB
On your PC, Go to the location where MongoDB is installed. I am using Windows 10 and its MongoDB installed location is C:\Program Files\MongoDB.Along the installation path, go to the bin folder like below.
Open the command line from that location and type mongod and hit Enter to start the MongoDB server. (If you have added the MongoDB path to the environmental variables you can use this command from any path.)
Open application.properties file and setup MongoDB configuration for your Spring Boot Project as follows.
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
spring.data.mongodb.database=School
Here I selected the database name as School. Next Open the MongoDB Compass.
Click Fill in connection fields individually. Then select the Hostname and Port as follows. After that, click CONNECT.
Now you can see your current MongoDB databases from MongoDB Compass.
As you can see I have not yet created a database named School as I mentioned in the application.properties file here. It will be created automatically when we send POST requests to the server.
Create a Model
In your Project Structure go to src -> main -> java -> [your package] .Click [your package] and hit Alt + Insert.
Create a new Java class named Student.
Now we are going to use this class as a Student Model. Every Student has a name and age. We also use a unique id of String type for each student.
package com.example.springmongodbdemo;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Getter
@Setter
@Document(collection = "Student")
public class Student {
@Id
String id;
String name;
int age;
}
Since we are using Lombok as a dependency, no need to enter getters and setters separately. We can include them using simple annotations @Getter and @Setter.I also entered the collection name as Student.
Create a Repository
Following the same method as mentioned above, create a new Java interface named StudentRepository.
Extend the interface by MongoRepository and give the Model name and id type as below. (If you are using a primary data type as id, then use the corresponding wrapper class.)
package com.example.springmongodbdemo;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface StudentRepository extends MongoRepository<Student,String> {
}
Create a Controller
Now Let’s create a Controller to send a POST Request. Create a class student Controller using the same method mentioned above.
package com.example.springmongodbdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
private StudentRepository studentRepository;
@Autowired
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@PostMapping(value = "/add")
public String addUser(@RequestBody Student student){
studentRepository.save(student);
return "User created successfully";
}
}
Using this POST request, we can add a new Student to the database. After adding a new Student, it will return a message “User created successfully.”
Run Spring Boot Project
Now we are finished with the program for creating POST requests. Click the Run button on the top section of the IDE to run the Spring Boot Project.
As you can see in your console, now our Spring Boot Application has started and it runs on port 8080.
Test
Open Postman and let’s create and send a POST request to the server. Select the Request type as POST and enter the request URL. Here I have sent Student as a JSON object.
Click Send to send the request to the server. You will get a response with a status code 200. It will say “User created successfully” message.
Now go to the MongoDB Compass and click the refresh button in the top left corner.
As you can see now, a new database named School has been created by our POST request.
Select the school database and there will be a collection named Student. Click it.
Now you can see that our student data has appeared in the database as we enter using Postman.
Congratulations ! you have successfully created a Spring Boot POST request using a MongoDB database.
See next Tutorial on How to make a Spring Boot PUT Request with MongoDB database using this link.