Boot

Spring Boot MongoDB Crud Operations Example

Welcome readers, in this tutorial, we will explore the MongoDB Crud operations in a spring boot application.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.1.1 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.

2. Spring Boot MongoDB Crud Operations Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MongoDB, and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Boot MongoDB Crud - Application Structure
Fig. 1: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Boot MongoDB Crud - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Boot MongoDB Crud -  Project Details
Fig. 3: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring Boot MongoDB Crud
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ducat.springboot.mongodb</groupId>
	<artifactId>SpringbootMongocrudoperations</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application. But before starting we are assuming that developers have installed the MongoDB on their machine.

3.1 Maven Dependencies

Here, we specify the dependencies for the Spring Boot and MongoDB. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ducat.springboot.mongodb</groupId>
	<artifactId>SpringbootMongocrudoperations</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	
	<name>SpringbootMongocrudoperations Maven Webapp</name>
	<url>http://maven.apache.org</url>
	
	<!-- spring boot parent dependency jar -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>
	
	<dependencies>
		<!-- spring boot web mvc jar -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- spring boot mongodb dependency. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>SpringbootMongocrudoperations</finalName>
	</build>
</project>

3.2 Application Properties

Create a new properties file at the location: SpringbootMongocrudoperations/src/main/resources/ and add the following code to it.

application.properties

# Application configuration.
server.port=8102

# Local mongodb configuration.
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=ducat-assignment

# Logging configuration.
logging.level.com.assignment.springboot.mongo=DEBUG
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n

3.3 Java Classes

Let’s write all the java classes involved in this application.

3.3.1 Implementation/Main class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

Myapplication.java

package com.assignment.springboot.mongo;

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

/**
 * Main implementation class which serves two purpose in a spring boot application: Configuration and bootstrapping.
 * @author yatin-batra
 */
@SpringBootApplication
public class Myapplication {

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

3.3.2 Model class

Add the following code to the employee model class.

Employee.java

package com.assignment.springboot.mongo.model;

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

// Mongo database annotation.
@Document(collection= "employee")
public class Employee {

	@Id
	private int id;
	private String name;
	private String designation;

	public Employee() {	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + "]";
	}
}

3.3.3 Data-Access-Object interface

Add the following code to the Dao interface that extends the Mongo Repository to automatically handle the crud queries.

Employeedao.java

package com.assignment.springboot.mongo.dao;

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

import com.assignment.springboot.mongo.model.Employee;

@Repository
public interface Employeedao extends MongoRepository<Employee, Integer> {

}

3.3.4 Service class

Add the following code to the service class where we will call the methods of the Dao interface to handle the sql operations.

Employeeservimpl.java

package com.assignment.springboot.mongo.service;

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

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

import com.assignment.springboot.mongo.dao.Employeedao;
import com.assignment.springboot.mongo.model.Employee;

@Service
public class Employeeserviceimpl implements Employeeservice {

	// The dao repository will use the Mongodb-Repository to perform the database operations.
	@Autowired
	Employeedao dao;

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#createEmployee(java.util.List)
	 */
	@Override
	public void createEmployee(List<Employee> emp) {
		dao.saveAll(emp);
	}

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#getAllEmployees()
	 */
	@Override
	public Collection<Employee> getAllEmployees() {
		return dao.findAll();
	}

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#findEmployeeById(int)
	 */
	@Override
	public Optional<Employee> findEmployeeById(int id) {
		return dao.findById(id);
	}

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#deleteEmployeeById(int)
	 */
	@Override
	public void deleteEmployeeById(int id) {
		dao.deleteById(id);
	}

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#updateEmployee(int)
	 */
	@Override
	public void updateEmployee(Employee emp) {
		dao.save(emp);
	}

	/* (non-Javadoc)
	 * @see com.assignment.springboot.mongo.service.Employeeservice#deleteAllEmployees()
	 */
	@Override
	public void deleteAllEmployees() {
		dao.deleteAll();
	}
}

3.3.5 Controller class

Add the following code to the controller class designed to handle the incoming requests. The class is annotated with the @RestController annotation where every method returns a domain object as a json response instead of a view.

Employeecontroller.java

package com.assignment.springboot.mongo.controller;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.assignment.springboot.mongo.model.Employee;
import com.assignment.springboot.mongo.service.Employeeservice;

@RestController
@RequestMapping(value= "/api/mongo/emp")
public class Employeecontroller {

	@Autowired
	Employeeservice serv;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * Method to save employees in the db.
	 * @param emp
	 * @return
	 */
	@PostMapping(value= "/create")
	public String create(@RequestBody List<Employee> emp) {
		logger.debug("Saving employees.");
		serv.createEmployee(emp);
		return "Employee records created.";
	}

	/**
	 * Method to fetch all employees from the db.
	 * @return
	 */
	@GetMapping(value= "/getall")
	public Collection<Employee> getAll() {
		logger.debug("Getting all employees.");
		return serv.getAllEmployees();
	}

	/**
	 * Method to fetch employee by id.
	 * @param id
	 * @return
	 */
	@GetMapping(value= "/getbyid/{employee-id}")
	public Optional<Employee> getById(@PathVariable(value= "employee-id") int id) {
		logger.debug("Getting employee with employee-id= {}.", id);
		return serv.findEmployeeById(id);
	}

	/**
	 * Method to update employee by id.
	 * @param id
	 * @param e
	 * @return
	 */
	@PutMapping(value= "/update/{employee-id}")
	public String update(@PathVariable(value= "employee-id") int id, @RequestBody Employee e) {
		logger.debug("Updating employee with employee-id= {}.", id);
		e.setId(id);
		serv.updateEmployee(e);
		return "Employee record for employee-id= " + id + " updated.";
	}

	/**
	 * Method to delete employee by id.
	 * @param id
	 * @return
	 */
	@DeleteMapping(value= "/delete/{employee-id}")
	public String delete(@PathVariable(value= "employee-id") int id) {
		logger.debug("Deleting employee with employee-id= {}.", id);
		serv.deleteEmployeeById(id);
		return "Employee record for employee-id= " + id + " deleted.";
	}

	/**
	 * Method to delete all employees from the db.
	 * @return
	 */
	@DeleteMapping(value= "/deleteall")
	public String deleteAll() {
		logger.debug("Deleting all employees.");
		serv.deleteAllEmployees();
		return "All employee records deleted.";
	}
}

4. Run the Application

As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the Myapplication.java class, Run As -> Java Application.

Spring Boot MongoDB Crud - Run the Application
Fig. 6: Run the Application

Developers can debug the example and see what happens after every step. Enjoy!

5. Project Demo

Open the postman tool and hit the following urls to display the data in the json format.

// Create new employee.
http://localhost:8102/api/mongo/emp/create

// Get all employees.
http://localhost:8102/api/mongo/emp/getall

// Find employee by id.
http://localhost:8102/api/mongo/emp/getbyid/1

// Update employee by id.
http://localhost:8102/api/mongo/emp/update/5

// Delete employee by id.
http://localhost:8102/api/mongo/emp/delete/1

// Delete all employees.
http://localhost:8102/api/mongo/emp/deleteall

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a Spring Boot application with MongoDB and perform the basic crud operations using the Spring JPA. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of implementing MongoDB with Spring Boot & Spring JPA.

Download
You can download the full source code of this example here: Spring Boot MongoDB Crud Operations Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

17 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andy
5 years ago

Good layout, nice and clear. I would however just add how to customise the @Repository in order to include custom queries that are not supplied out of the box with Spring Data.

Thomas C Buell
Thomas C Buell
5 years ago

I ran the Spring Boot Mongo db project but I’m receiving an error when I’m running it as a Java Application from MyApplication.java. 2019-04-02 08:19:38 – Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ’employeecontroller’: Unsatisfied dependency expressed through field ‘serv’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.assigment.springboot.mongo.service.Employeeservice’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2019-04-02 08:19:38 – Stopping service [Tomcat] 2019-04-02 08:19:38 – Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled. 2019-04-02 08:19:38 – *************************** APPLICATION… Read more »

Thomas C Buell
Thomas C Buell
5 years ago

One more question. I don’t see the Employeeservice.java class being created in the screenshots.

mohamed
mohamed
5 years ago
Reply to  Thomas C Buell

me too ?!

gaurav dabade
gaurav dabade
5 years ago

How to run this application on postman. I am getting this error on postman.
{
“timestamp”: “2019-05-23T06:09:25.531+0000”,
“status”: 400,
“error”: “Bad Request”,
“message”: “JSON parse error: Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]”,
“path”: “/api/mongo/emp/create”
}

Yatheesh
Yatheesh
5 years ago
Reply to  Yatin

I have the same issue, what is the resolution? I have downloaded the project just to make sure am not missing anything but still /create API is giving json parser error

Gautam
Gautam
5 years ago
Reply to  gaurav dabade

try like below
[
{
“id”: 123,
“name”: “Rohit”,
“designation”: “SR”
}
]

Gayan Ramya Kumara
Gayan Ramya Kumara
5 years ago

Great tutorial.
please share the form validation related lesson.

Vineetha
Vineetha
5 years ago

I’m getting an error in postman

“timestamp”: “2019-10-20T11:27:44.909+0000”,
“status”: 400,
“error”: “Bad Request”,
“message”: “Required request body is missing: public java.lang.String com.assignment.springboot.mongo.controller.Employeecontroller.create(java.util.List)”,
“path”: “/api/mongo/emp/create”

jyothi
jyothi
4 years ago

I am getting error like this may know issue how to solve this
Error: connect ECONNREFUSED 127.0.0.1:8080
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.26.3
Accept: */*
Postman-Token: b2a63e3c-288e-4b41-8648-40de404e8789
Host: localhost:8080
Accept-Encoding: gzip, deflate, br

Back to top button