Pages

Thursday, May 7, 2020

Spring Boot MongoDB CRUD Operations Example

1. Introduction


In this tutorial, You'll learn how to do CRUD operations in MongoDB database as part of the Spring Boot Application.

MongoDB is a NoSQL database that uses JSON as a schema.

CRUD operations have been considered in computer programming as create, read, update, and delete (CRUD) are the four basic functions of persistent storage

Another example of How to generate auto-increment id in MongoDB Spring Boot App

Let us see step by step how to do it in a simple way.

Spring Boot MongoDB CRUD Operations Example




MongoDB CRUD Examples in Spring Boot App


2. Adding Dependencies for MongoDB CRUD Operations

Add the web, MongoDB, and Lombok dependencies to the spring boot project.

  • spring-boot-starter-web
  • spring-boot-starter-data-mongodb
  • org.projectlombok&
[post_ads]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.2.6.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.javaprogramto.springboot</groupId>
 <artifactId>MongoDB-Spring-Boot-CURD</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>MongoDB-Spring-Boot-CURD</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
    <exclusion>
     <groupId>org.junit.vintage</groupId>
     <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>


3. Creating a DataBase and Collection (Table) with MongoDB Compass


Open the "MongoDB Compass" Gui and create a database along with the collection name "Employee".

MongoDB Compass GUI will allow us to create, add, or delete the data and visualize, debug, and optimize the data easily with the interface rather than doing the things with the script.

We are going to perform all CRUD operations on the Employee table.

Creating a DataBase and Collection (Table) with MongoDB Compass


No columns were added to the collection or table as of now. And also we are not going to create anything in this article. But if you want to add columns, you can add them as need.

Whatever the object is passing to the MongoDB, based on the object properties columns will be added to the Employee table.

4. Creating Model Class - To store the data into MongoDB


We've already injected the Lombok dependency which makes the code simple and easy to main with the annotations rather than keep much code in the class.

@Getter annotation to generate the getter methods at runtime.
@Setter annotation to generate the setter methods at runtime
@ToString to generate the toString() method with all the properties and its values.

And also linking this model to MongoDB table with @Document annotation and specify the table name with collection attribute to tell the table name as "Employee"


package com.javaprogramto.springboot.model;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

@Getter@Setter@ToString
@Document(collection = "Employee")
public class Employee {

    @Id    
    private int id;
    private String name;
    private int age;
    private long phoneNumber;
    private Date dateOfJoin;


}


5. Create Repository - CRUD Operations with MongoRepository<Employee, Integer>


Let us create a package with the repository and create an interface with the name "EmployeeRepository".
This interface must extend the built-in MongoReposity<T, ID>.

Here T is the type of the object that CURD operations to be performed on and ID is the primary key that is used for fetching.

package com.javaprogramto.springboot.MongoDBSpringBootCURD.repository;

import com.javaprogramto.springboot.model.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface EmployeeRepository extends MongoRepository<Employee, Integer> {

    
}

Inside EmployeeRepositiry interface, We did not add any methods because all basic methods come from MongoRepository.
[post_ads]

6. Create Controller - API Endpoints for Doing CRUD Operations in MongoDB


Create a class with any name, but here created as "EmployeeController" and it should be annotated with @RestController annotation.

And also need to provide the URL mapping with annotation @RequestMapping.

All these annotations are should be applied at the class level.

package com.javaprogramto.springboot.MongoDBSpringBootCURD.controller;

import com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee;
import com.javaprogramto.springboot.MongoDBSpringBootCURD.repository.EmployeeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping
("/employee")

public class EmployeeController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private EmployeeRepository employeeRepository;

    @PostMapping
("/add")
    public String saveEmployee(@RequestBody Employee e) {


        employeeRepository.insert(e);

        return "Added Employee id " + e.getId();
    }

    @GetMapping("/find/{id}")

    public Optional<Employee> getEmployee(@PathVariable int id) {

        logger.info("find employee by id : "+id);
        Optional<Employee> emp = employeeRepository.findById(id);

        return emp;
    }

    @GetMapping("/all")

    public List<Employee> getAllEmployee() {

        List<Employee> allEmployees = employeeRepository.findAll();

        return allEmployees;
    }

    @DeleteMapping("/delete/{id}")

    public String deleteEmployee(@PathVariable int id) {

        employeeRepository.deleteById(id);

        return "Delete emp for id " + id;
    }

    @PutMapping("/update")

    public String updateEmployee(@RequestBody Employee e) {

        employeeRepository.save(e);

        return "Updated Employee for id " + e.getId();
    }
}

This example is having all the CURD operations.

6.1 Create or Insert Operation


Create a post request that is mapped to the "/add" URL. When hitting this URL employe should be passed as JSON that will be mapped to Employee object with @RequestBody.


@PostMapping("/add")

public String saveEmployee(@RequestBody Employee e) {

    employeeRepository.insert(e);

    return "Added Employee id " + e.getId();
}

[post_ads]

6.2 Read Operations


Get All Employees:

@GetMapping("/all")

public List<Employee> getAllEmployee() {

    List<Employee> allEmployees = employeeRepository.findAll();

    return allEmployees;
}

Get Employee By Id:


@GetMapping("/find/{id}")


public Optional<Employee> getEmployee(@PathVariable int id) {

    logger.info("find employee by id : "+id);
    Optional<Employee> emp = employeeRepository.findById(id);

    return emp;
}

6.3 Update Operation


Updating an existing employee

@PutMapping("/update")

public String updateEmployee(@RequestBody Employee e) {

    employeeRepository.save(e);

    return "Updated Employee for id " + e.getId();
}

6.4 Delete Operation


Deleting an existing employee

@DeleteMapping("/delete/{id}")


public String deleteEmployee(@PathVariable int id) {

    employeeRepository.deleteById(id);

    return "Delete emp for id " + id;
}

7. Configuring the MongoDB in the Spring Boot Application


Before starting the application, we need to configure MongoDB NoSQL database details in the application.properties file as below.

If you don't port and database name, you can get the port from log or console and database name from MongoDB Compass GUI.

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


8. Testing the CRUD Operations of Spring Boot MongoDB


We used postman for testing and which is more flexible to test all endpoints.

Add: localhost:8080/employee/add
Delete by id : localhost:8080/employee/delete/100
Find by id: Delete: localhost:8080/employee/find/100
Find all: Delete: localhost:8080/employee/all
Update: localhost:8080/employee/update

[post_ads]

8.1 Add or Create Operation with PostMan Tool


spring-boot-mongodb-add-crud-operation-min



8.2 Read Operation - Get All Employees with PostMan Tool


spring-boot-mongodb-get-all-crud-operation-min


[post_ads]

8.3 Read Operation - Get Employee By Id -  with PostMan Tool


spring-boot-mongodb-find-by-id-crud-operation-min

8.4 Update Employee -  with PostMan Tool


Employee table before update

employee-table-records-before-update-200-min


Updating employee id 200 name and phone number values.
[post_ads]

spring-boot-mongodb-update-crud-operation-min


Employee table After successful update.

employee-table-records-after-update-200-min

8.5 Delete Operation with PostMan Tool


Deleting employee id = 100

spring-boot-mongodb-delete-crud-operation-min

Employee table after delete.
[post_ads]

deleted-employee-id-100-min



9. Exceptions in MongoDB CRUD Operations Spring Boot


If you invalid number to phone number filed with spaces or special characters then you will face the below error at run time

2020-05-07 20:11:02.155  WARN 36206 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `long` from String "+1 6778 100 100": not a valid Long value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `long` from String "+1 6778 100 100": not a valid Long value

 at [Source: (PushbackInputStream); line: 6, column: 16] (through reference chain: com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee["phoneNumber"])]

2020-05-07 20:11:16.038  WARN 36206 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `long` from String "1 6778 100 100": not a valid Long value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `long` from String "1 6778 100 100": not a valid Long value

 at [Source: (PushbackInputStream); line: 6, column: 16] (through reference chain: com.javaprogramto.springboot.MongoDBSpringBootCURD.model.Employee["phoneNumber"])]

10. SpringBoot MongoDB Project Structure

├── HELP.md
├── MongoDB-Spring-Boot-CURD.iml
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── javaprogramto
│   │   │           └── springboot
│   │   │               └── MongoDBSpringBootCURD
│   │   │                   ├── MongoDbSpringBootCurdApplication.java
│   │   │                   ├── controller
│   │   │                   │   └── EmployeeController.java
│   │   │                   ├── model
│   │   │                   │   └── Employee.java
│   │   │                   └── repository
│   │   │                       └── EmployeeRepository.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates


11. Conclusion



In conclusion, You've seen how to build the CRUD operations with MongoDB in the Spring Boot application.


Example of how to add all endpoints implemented for insertion, deletion, update and find operations.

Screenshots for all operations are shown.


All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.