Spring Boot MongoDB CRUD example

Spring Boot MongoDB CRUD example

step1 : create project

step 2: create packages

directory structure

step 3 : application.properties


spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=newdb

spring.jpa.hibernate.ddl-auto=update

step 4 : entity

Employee.java

package com.example.demo.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@Document
@AllArgsConstructor
public class Employee {
    @Id
    private String id;
    private String ename;
    private String dept;
    private Double sal;
    private Float age;
    private Long contactNo;
}

step 5 : create repository

EmployeeRepository.java

package com.example.demo.repo;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.example.demo.entity.Employee;

public interface EmployeeRepository extends MongoRepository<Employee, String>{

}

step 6 : create services

EmployeeMgmtService.java

package com.example.demo.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.entity.Employee;
import com.example.demo.repo.EmployeeRepository;

@Service
public class EmployeeMgmtService {

    @Autowired
    private EmployeeRepository repo;

    // save operation
    public String saveEmployee(Employee emp) {
        return "Emp saved with id : " + repo.save(emp).getId();
    }

    // batch insertion
    public String saveEmpGroup(List<Employee> emps) {
        return repo.saveAll(emps).size() + " employees saved";
    }

    // fetch all documents of the collection
    public List<Employee> fetchAllEmp() {
        return repo.findAll();
    }

    // fetch document by id
    public Optional<Employee> fetchTouristById(String id) {
        return repo.findById(id);
    }

    // updating the emp
    public String modifyEmpById(String id, long contactNo) {
        Optional<Employee> opt = repo.findById(id);
        if (opt.isPresent()) {
            Employee emp = opt.get();
            emp.setContactNo(contactNo);
            return repo.save(emp).getId() + " is updated";
        } else {
            return "Document no found";
        }
    }

    // removing the document
    public String removeEmployeeById(String id) {
        Optional<Employee> opt = repo.findById(id);
        if (opt.isPresent()) {
            Employee emp = opt.get();
            repo.delete(emp);
            return "Document is found and deleted";
        } else {
            return "Document not found";
        }
    }
}

step 7 : runner

TestRunner.java

package com.example.demo.runner;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeMgmtService;

@Component
public class TestRunner implements CommandLineRunner{

    @Autowired
    private EmployeeMgmtService service;

    @Override
    public void run(String... args) throws Exception {
        //1.save single emp
        System.out.println(service.saveEmployee(new Employee(null,"sam","dev",5000.0,45.0f,55667788L)));

        //2.batch insertion
        Employee emp1 = new Employee(null,"Jhon","qa",6000.0,null,55669988L);
        Employee emp2 = new Employee(null,"Anglea","qa",7000.0,null,null);
        List<Employee> empList = List.of(emp1,emp2);
        System.out.println(service.saveEmpGroup(empList));

        //3.fetch all the cocuments
        service.fetchAllEmp().forEach(System.out::println);

        //4.fetch doc by id
        Optional<Employee> opt = service.fetchTouristById("639eba5845f78a278af1aa96");
        if(opt.isPresent()) {
            System.out.println(opt.get());
        }else {
            System.out.println("Emp not present");
        }

        //5. modify the emp by id
        System.out.println(service.modifyEmpById("639eba5845f78a278af1aa96",99778822L));

        //6. remove the document by id
        System.out.println(service.removeEmployeeById("639eba5845f78a278af1aa96"));


    }

}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootMongoCrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMongoCrudApplication.class, args);
    }

}

step 8 : run SpringBootMongoCrudApplication.java

Did you find this article valuable?

Support realNameHidden by becoming a sponsor. Any amount is appreciated!