In this article, we are going to see how we can perform crud operations with Spring Boot and MongoDB
Creating spring boot application
The first step is to create a spring boot application we MongoDB dependency. For creating a spring boot application using the spring boot initializer and all required dependencies with MongoDB dependencies for spring boot and also add dependencies for lombok.
Spring Boot MongoDB dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
After creating the spring boot project with all required dependencies. We are first going to create a mongo repository but we need a model class. So first create a model class. Our model class is about student and we store basic details of student.
Model Class
As our model class is for the student, so we will make the student id as primary key and roll no is unique. for making roll no unique in MongoDB with spring boot we need to use @Indexed(unique=true) with spring.data.mongodb.auto-index-creation=true in application.properties file and @Id will work for primary key
Model.java
package com.gangforcode.MongoDBSpringBoot.model; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Data @Document("students") public class Student { @Id private String studentId; @Indexed(unique = true) private int rollNo; private String name; private String grade; }
MongoDB Repository
Let’s create a mongo repository by extending MongoRepository. And declare a method findByRollNo in this.
Repository.java
package com.gangforcode.MongoDBSpringBoot.repo;
import com.gangforcode.MongoDBSpringBoot.model.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface Repository extends MongoRepository<Student,String> {
}
MongoDB configuration
Add the following lines in the application.properties file
spring.data.mongodb.uri=mongodb://localhost:27017/student spring.data.mongodb.database=Student spring.data.mongodb.auto-index-creation=true
You can specify database name as you want.
now everything is completed, now we have to write the logic for the crud operation. Here we will write all the logic in the controller but you can create a service class if you want.
Controller
Now create a controller and inside the controller auto wire the repository.
package com.gangforcode.MongoDBSpringBoot.controller;
import com.gangforcode.MongoDBSpringBoot.repo.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/student")
public class Controller {
@Autowired
private Repository repository;
}
Add Student
first logic we are going to write for adding a student; Add following code in controller here we directly adding the student details into database, but if you want you can validate the details of student.
@PostMapping("add")
public Student add(@RequestBody Student student)
{
try{
Student std = repository.save(student);
return std;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Get All Student
@GetMapping("/findAll") public List<Student> findAll() { return repository.findAll(); }
Get Student by roll no.
@GetMapping("/findAll")
public List<Student> findAll()
{
return repository.findAll();
}
Update Student Details
@PutMapping("/update/{studentId}")
public Student update(@PathVariable String studentId , @RequestBody Student student)
{
Optional<Student> std = repository.findById(studentId);
if(std.isPresent())
{
Student update = std.get();
update.setGrade(student.getGrade());
update.setName(student.getName());
update.setRollNo(student.getRollNo());
return repository.save(update);
}
return null;
}
Delete Student
@DeleteMapping("/delete/{studentId}")
public String delete(@PathVariable String studentId)
{
Optional<Student> student = repository.findById(studentId);
if(student.isPresent()) {
repository.deleteById(studentId);
return "successfully deleted";
}
return "Already Deleted";
}
}
2 thoughts on “Spring boot MongoDB Tutorial”