Spring Boot MongoDB CRUD RestAPIs Example – using MongoDB Atlas

SpringBoot MongoDB CRUD RestAPIs Example

SpringBoot Tutorial: “Spring Boot MongoDB CRUD RestAPIs Example – using MongoDB Atlas”.

How to integrate SpringBoot and MongoDB? It is the one of most common questions for developers. So in the tutorial, I will help you to try it using SpringData MongoDB and SpringBoot RestAPIs with a “Spring Boot MongoDB CRUD RestAPIs Example” project. Here is a to do list for the tutorial:

– I draw an overview diagram architecture for SpringBoot and MongoDB database.
– Explain a hierarchy diagram of MongoRepository and CrudRepository.
– Guide step by step with clearly and running coding examples for how to create a SpringBoot MongoDB Crud RestAPIs.
– Create an integrative testsuite with Post/get/put/delete requests from Postman client to MongoDB Atlas through SpringBoot RestAPIs.

Related posts:


Overview Diagram Architecture – How to build Spring Boot MongoDB CRUD RestAPIs Example

SpringBoot MongoDB CRUD RestAPI Fullstack Diagram Architecture
SpringBoot MongoDB CRUD RestAPI Fullstack Diagram Architecture

In the tutorial, I build a SpringBoot project that handle all Post/Get/Put/Delete requests from RestClient and do CRUD operations to MongoDB Atlas database to save/retrieve/update and delete documents from MongoDB and returns back to Restclient the corresponding messages.

We build a SpringBoot project with 3 layers:
– MongoDB Repository is used to interact with MongoDB database by a set of CRUD operations.
– Service is the middle-ware layer for interating with RestController layer and MongoDB Repository layer. This is a transforming machine, it gets the needed data from web-requests through RestController and do CRUD operation to MongoDB via MongoDB Repository layer.
– RestController layer is a web layer for SpringBoot project, it will directly handle all incomming requests and do the corressponding responses to the calling client.

SpringBoot Interface Repository MongoRepository

To do the CRUD operations with MongoDB database, we use the built-in machine MongoRepository of SpringBoot framework. MongoRepository extends the PagingAndSortingRepository:

MongoRepository Hierarchy Diagram
MongoRepository Hierarchy Diagram

PagingAndSortingRepository extends the CrudRepository:

SpringBoot CrudRepository hierarchy diagram
SpringBoot CrudRepository hierarchy diagram

– Here is a list methods of CrudRepository:

CrudRepository methods
CrudRepository methods

– Here is a list methods of MongoRepository:

MongoRepository methods
MongoRepository methods

– Here is a list methods of PagingAndSortingRepository:

List methods of PagingAndSortingRepository
List methods of PagingAndSortingRepository

How to build SpringBoot MongoDB CRUD RestAPI project

Now it’s time for building the “SpringBoot MongoDB CRUD RestAPIs Example” project with a set of simple steps:

  • Create SpringBoot project
  • Configure MongoDB Database
  • Define Spring Data MongoDB’s Document Model
  • Define SpringBoot MongoDB Repository
  • Implement SpringBoot Customer Service
  • Implement SpringBoot MongoDB CRUD RestAPIs

Let’s go!

Create SpringBoot MongoDB project

We use SpringToolSuite to create a simple SpringBoot project with below structure:

SpringBoot MongoDB CRUD RestAPIs project structure
SpringBoot MongoDB CRUD RestAPIs project structure
  • application.properties is used to add the SpringBoot application’s configurations such as: database configuration (MongoDB, MySQL, PostgreSQL), threadpool, Hibernate, JPA …
  • repository package is used to define a SpringBoot MongoDB repository to do CRUD operations with MongoDB
  • rest package is used to implement a SpringBoot RestAPI controller to handle all incomming requests (post/get/put/delete) and response to rest-client.
  • service package is used to implement a middleware machine between RestAPIs controller and Mongo Repository of SpringBoot project.
  • model package is used to define the MongoDB document’s schema that maps with the document format in MongoDB database

For handling the web-request and doing CRUD operations with MongoDB database, we need the supporting of 2 SpringBoot dependencies: spring-boot-starter-web and spring-boot-starter-data-mongodb. So adding it to pom.xml file:

<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>

SpringBoot Configure MongoDB Database

To initialize a connection with MongoDB Atlas, we open the file application.properties and add below uri configure:

#mongodb
spring.data.mongodb.uri=mongodb+srv://loizenjava:loizenjava@cluster0.gmd7e.mongodb.net/loizenjavadb?retryWrites=true&w=majority

Define Spring Data MongoDB’s Document Model

Now we define a Customer class for mapping data between SpringBoot application with MongoDB documents:

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

@Document(collection = "customers")
public class Customer {
	@Id
	private String id;
	private String firstname;
	private String lastname;
	private Integer age;
	private String address;
	private Double salary;
	
	@Field
	private String copyrightby = "https://loizenjava.com";

	public Customer(String firstname, String lastname, int age, String address, Double salary) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
		this.address = address;
		this.salary = salary;
	}
        // getters and setters 
        // ...

@Document is used to identify a domain object to be persisted to MongoDB.

Here is a sample domain object to be persisted to MongoDB:

MongoDB Document schema
MongoDB Document schema

Define SpringBoot MongoDB Repository

– Create a CustomerRepository interface that extends MongoRepository:

package com.loizenjava.springboot.mongodb.repository;

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

import com.loizenjava.springboot.mongodb.model.Customer;

public interface CustomerRepository extends MongoRepository<Customer, String>{
}

With the CustomerRepository interface, we can do all CRUD operations (save/retrieve/update/delete) from SpringBoot application to MongoDB database.

Implement SpringBoot Customer Service

Now we implement a middle service between RestController layer and MongoDB Repository, by creating a file CustomerService that uses mongodb repository CustomerRepository as below code:

package com.loizenjava.springboot.mongodb.service;

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

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

import com.loizenjava.springboot.mongodb.exception.CustomException;
import com.loizenjava.springboot.mongodb.model.Customer;
import com.loizenjava.springboot.mongodb.repository.CustomerRepository;

@Service
public class CustomerService {
	
	@Autowired
	CustomerRepository repo;
	
	public Customer saveCustomer(Customer customer){
		return repo.save(customer);
	}
	
	public List<Customer> saveListCustomers(List<Customer> customers) {
		return repo.saveAll(customers);
	}
	
	public List<Customer> retrieveAllCustomers(){
		return repo.findAll();
	}
	
	public Optional<Customer> getCustomerByID(String id) {
		return repo.findById(id);
	}
	
	public Customer updateCustomer(String id, Customer customer) throws CustomException {
		
		Optional<Customer> customerOpt = repo.findById(id);
		
		if(!customerOpt.isPresent()) {
			throw new CustomException("404", "Can not find a customer for updating with id = " + id);
		}
			
		Customer _customer = customerOpt.get();
		
		_customer.setFirstname(customer.getFirstname());
		_customer.setLastname(customer.getLastname());
		_customer.setAddress(customer.getAddress());
		_customer.setAge(customer.getAge());
		_customer.setSalary(customer.getSalary());
		
		repo.save(_customer);
		
		return _customer;
	}
	
	public void deleteCustomerById(String id) {
		repo.deleteById(id);
	}
	
	public void deleteAll() {
		repo.deleteAll();
	}
}

Implement SpringBoot MongoDB CRUD RestAPIs

Related post: SpringBoot RestAPIs @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping

We use SpringWeb to implement 7 RestAPIs for Post/Get/Put/Delete requests as below list:

  • SpringBoot Post request – we define 2 restapis:
    /api/customer/create is used to save a single Customer data to MongoDB database.
    /api/customer/create/v2 is used to save a list of multiple Customer data to MongoDB database.
  • SpringBoot Get request – we define 2 restapis:
    /api/customer/getone/{id} is used to retrieve a single Customer document from MongoDB database via a given id
    /api/customer/all is used to retrieve all Customer documents from MongoDB database.
  • SpringBoot Put request – we define a restapi /api/customer/update/{id} to update a Customer document from MongoDB via a given id and request body’s data
  • SpringBoot Delete request – we define 2 restapis:
    /api/customer/deletebyid/{id} is used to delete a Customer document from MongoDB via a give id
    /api/customer/deleteall is used to delete all Customer documents from MongoDB database.
@RestController
@RequestMapping("/api/customer")
public class WebController {
	
	@Autowired
	CustomerService customerService;

	@PostMapping("/create")
	public ResponseEntity<ResponseMsg> saveCustomer(@RequestBody Customer customer, HttpServletRequest request) {
		...
	}
	
	@PostMapping("/create/v2") 
	public ResponseEntity<ResponseMsg> saveListCustomers(@RequestBody List<Customer> customers, HttpServletRequest request) {
		...
	}
	
	@GetMapping("/all")
	public ResponseEntity<ResponseMsg> getAllCustomers(HttpServletRequest request) {
		...
	}

	@GetMapping("/getone/{id}")
	public ResponseEntity<ResponseMsg> getCustomerById(@PathVariable String id, HttpServletRequest request) {
		...
	}
	
	@PutMapping("/update/{id}")
	public ResponseEntity<ResponseMsg> updateCustomer(@PathVariable String id, @RequestBody Customer customer,
															HttpServletRequest request) {
		...
	}
	
	@DeleteMapping("/deletebyid/{id}")
	public ResponseEntity<ResponseMsg> deleteCustomerById(@PathVariable String id, HttpServletRequest request) {
		...
	}

	@DeleteMapping("/deleteall")
	public ResponseEntity<ResponseMsg> deleteAllCustomers(HttpServletRequest request){
		...
	}
}

As above code, the SpringBoot RestController uses the implemented CustomerService to interact with under-layer MongoDB database for doing CRUD operations.

Let’s go to implement the details coding!

Implement SpringBoot MongoDB Post request

We define a simple ResponseMsg class for SpringBoot’s response body:


public class ResponseMsg {
	private String message;
	private String url;
	private String error = "";
	private List<Customer> customers = new ArrayList<Customer>();
	
	public ResponseMsg(String message, String url, List<Customer> customers) {
		this.message = message;
		this.url = url;
		this.customers = customers;
	}
	
	public ResponseMsg(String message, String url, String error) {
		this.message = message;
		this.url = url;
		this.error = error;
	}
	
	public ResponseMsg(String message, String url) {
		this(message, url, List.of());
	}

– Implement a SpringBoot RestAPIs to handle a POST request to save a single object to MongoDB database:

@PostMapping("/create")
public ResponseEntity<ResponseMsg> saveCustomer(@RequestBody Customer customer, HttpServletRequest request) {
	try {
		// save to MongoDB database
		Customer _customer = customerService.saveCustomer(customer);
		
		String message = "Upload Successfully a Customer to MongoDB with id = " + _customer.getId();
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
										List.of(customer)), HttpStatus.OK);	
	}catch(Exception e) {
		String message = "Can NOT upload  a Customer to MongoDB database";
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
										e.getMessage()), HttpStatus.OK);
	}
}

– Implement a SpringBoot RestAPIs to handle Post request to save multiple objects to MongoDB database:

@PostMapping("/create/v2") 
public ResponseEntity saveListCustomers(@RequestBody List customers, HttpServletRequest request) {
	try {
		// save a list of customers to MongoDB database
		List _customers = customerService.saveListCustomers(customers);
		
		String message = "Upload Successfully a list of Customer to MongoDB";
		return new ResponseEntity(new ResponseMsg(message, request.getRequestURI(), _customers), HttpStatus.OK);	
	}catch(Exception e) {
		String message = "Can NOT upload a List of Customer to MongoDB database";
		return new ResponseEntity(new ResponseMsg(message, request.getRequestURI(), 
													e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

Implement SpringBoot MongoDB Get request

– Implement a SpringBoot restapi to get a single document from MongoDB database by a given id:

@GetMapping("/getone/{id}")
public ResponseEntity<ResponseMsg> getCustomerById(@PathVariable String id, HttpServletRequest request) {
	try {
		// get a document from MongoDB database using ID
		Optional<Customer> customerOpt = customerService.getCustomerByID(id);
		
		if(customerOpt.isPresent()) {
			String message = "Successfully get a Customer from MongoDB with id = " + id;
			return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
									List.of(customerOpt.get())), HttpStatus.OK);
		} else {
			String message = "Fail! Not FOUND a Customer from MongoDB with id = " + id;
			return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
														"NOT FOUND"), HttpStatus.NOT_FOUND);
		} 
	}catch(Exception e) {
		String message = "Can NOT get a Customer from MongoDB database with id = " + id;
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
													e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

– Implement a SpringBoot restapi to get all document from MongoDB database:

@GetMapping("/all")
public ResponseEntity<ResponseMsg> getAllCustomers(HttpServletRequest request) {
	try {
		// get all documents from MongoDB database
		List<Customer> customers = customerService.retrieveAllCustomers();
		
		String message = "Retrieve all Customer successfully!";
		
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, 
								request.getRequestURI(), customers), HttpStatus.OK);	
	}catch(Exception e) {
		String message = "Can NOT retrieve all data from MongoDB database";
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), 
								e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

Implement SpringBoot MongoDB Put request

– Implement a SpringBoot restapi to update a MongoDB document via a given id and data from request body:

@PutMapping("/update/{id}")
public ResponseEntity<ResponseMsg> updateCustomer(@PathVariable String id, @RequestBody Customer customer,
														HttpServletRequest request) {
	try {
		// update a customer to MongoDB
		Customer _customer = customerService.updateCustomer(id, customer);
		String message = "Successfully Update a Customer to MongoDB with id = " + id;
		
		return new ResponseEntity<ResponseMsg> (new ResponseMsg(message, request.getRequestURI(), 
													List.of(_customer)), HttpStatus.OK);
	} catch (CustomException ce) {
		String message = "Can NOT update to MongoDB a Customer with id = " + id;
		return new ResponseEntity<ResponseMsg> (new ResponseMsg(message, request.getRequestURI(), 
				ce.getMessage()), HttpStatus.NOT_FOUND);
	} catch (Exception e) {
		String message = "Can NOT update to MongoDB a Customer with id = " + id;
		return new ResponseEntity<ResponseMsg> (new ResponseMsg(message, request.getRequestURI(), 
				e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

Implement SpringBoot MongoDB Delete request

– Implement a SpringBoot Delete restapi – delete a single document from MongoDB via a given id:

@DeleteMapping("/deletebyid/{id}")
public ResponseEntity<ResponseMsg> deleteCustomerById(@PathVariable String id, HttpServletRequest request) {
	try {
		// delete a Customer from MongoDB database using ID
		customerService.deleteCustomerById(id);
		
		String message = "Successfully delete a Customer from MongoDB database with id = " + id;
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI()), HttpStatus.OK);
	} catch(Exception e) {
		String message = "Can Not delete a Customer from MongoDB database with id = " + id;
		return new ResponseEntity<ResponseMsg>(new ResponseMsg(message, request.getRequestURI(), e.getMessage()), 
													HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

– Implement a SpringBoot Delete request – delete all documents from MongoDB:


@DeleteMapping("/deleteall")
public ResponseEntity<ResponseMsg> deleteAllCustomers(HttpServletRequest request){
	String message = "";
	try {
		customerService.deleteAll();
		
		message = "Successfully delete all Customer from MongoDB database!";
		return new ResponseEntity<ResponseMsg> (new ResponseMsg(message, 
										request.getRequestURI()), HttpStatus.OK);
	} catch(Exception e) {
		message = "Can NOT delete All documents from MongoDB database";
		return new ResponseEntity<ResponseMsg> (new ResponseMsg(message, 
						request.getRequestURI(), e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

Integrative Testing – SpringBoot MongoDB CRUD RestAPIs testsuite

Testcase 1 – Post request – Save a single object to MongoDB

Testcase 1 SpringBoot MongoDB Crud - Post request - save a single data to Mongo Atlas database
Testcase 1 SpringBoot MongoDB Crud – Post request – save a single data to Mongo Atlas database

Testcase 2 – Post request – Save multiple objects to MongoDB

Testcase 2 - SpringBoot MongoDB Crud restapi - Post request - Post a list of data to MongoDB Atlas database
Testcase 2 – SpringBoot MongoDB Crud restapi – Post request – Post a list of data to MongoDB Atlas database

– Check MongoDB after posting:

Check MongoDB documents
Check MongoDB documents

Testcase 3 – Get request – retrieve all documents from MongoDB

Testcase 3 - SpringBoot MongoDB CRUD restapi - Get request - retrieve all data from MongoDB
Testcase 3 – SpringBoot MongoDB CRUD restapi – Get request – retrieve all data from MongoDB

Testcase 4 – Get request – retrieve a single document from MongoDB

Testcase 4 - SpringBoot MongoDB Crud RestApis - Get request - retrieve a single document from MongoDB Atlas database
Testcase 4 – SpringBoot MongoDB Crud RestApis – Get request – retrieve a single document from MongoDB Atlas database

Testcase 5 – Put request – SpringBoot RestAPI updates data to MongoDB

Testcase 5 - SpringBoot MongoDB Crud restapi - Put request - update a data to MongoDB Atlas database
Testcase 5 – SpringBoot MongoDB Crud restapi – Put request – update a data to MongoDB Atlas database

– Check MongoDB document after updating:

MongoDB update a document successfully
MongoDB update a document successfully

Testcase 6 – Delete request – SpringBoot RestAPI delete a single document from MongoDB

Testcase 6 - SpringBoot MongoDB CRUD - Delete request - remove a single document by id from MongoDB
Testcase 6 – SpringBoot MongoDB CRUD – Delete request – remove a single document by id from MongoDB

Testcase 7 – Delete request – SpringBoot RestAPI delete all documents in MongoDB

Testcase 7 - SpringBoot MongoDB Crud RestAPIs - delete all documents in MongoDB database
Testcase 7 – SpringBoot MongoDB Crud RestAPIs – delete all documents in MongoDB database

Sourcecode

Below is a running sourcecode for the tutorial: “Spring Boot MongoDB CRUD RestAPIs Example – using MongoDB Atlas”.

SpringBoot MongoDB CRUD RestAPIs Example

– GitHub Sourcecode:

SpringBoot MongoDB CRUD RestAPIs Example

Further Reading

Should Reading:


Leave a Reply

Your email address will not be published. Required fields are marked *