Home » Framework » Spring Boot Application with CRUD in MongoDB

Spring Boot Application with CRUD in MongoDB

This article explains how to perform basic curd operations in MongoDB through Spring Boot Application. Let me explain what all we need to do for that.

The first thing is we need to create a project in Spring Initializr with the needed dependencies. So before doing it please make sure these essentials are installed in your system.

Essential Software : Eclipse, MongoDB.

Let's start to create a spring boot application with MongoDB enabled. Please go to the Spring Initializr website. You have to choose Project Type, Spring Boot Version, Project Metadata, Packaging, Java Version, and Maven Decencies we need. Then click Generate button to generate your project. It downloads the project in zip format.

Here in this project I have added two dependencies spring web and spring data MongoDB and chose the packaging type as war. Now let's start to configure the downloaded project in eclipse.

How to configure Spring Boot Application in Eclipse

In eclipse right-click the project explorer and chose the import option then select existing maven projects. it asks you to put the root directory of your project so please put the project path and click finish. Now you successfully configured your Spring Boot Maven Project in Eclipse.

Let start to create the rest API'S to perform CRUD Operation in MongoDB. The Project Structure is below.

Spring Boot Project Structure
Spring Boot Project Structure

pom.xml file with maven dependencies below

<?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.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.tipstocode</groupId>
	<artifactId>springbootmongocrud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>springbootmongocrud</name>
	<description>Spring Boot With MongoDB CRUD</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-starter-tomcat</artifactId>
			<scope>provided</scope>
		</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>

MongoDB Configuration in application.properties file

#spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=root
#spring.data.mongodb.password=
spring.data.mongodb.database=mongo_crud
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

Here i used below ProfileVO.java bean to perform crud operation in mongodb.

package com.tipstocode.model;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "user_profile")
public class ProfileVO {	
	@Id
	private ObjectId _id;	
	private String firstName;	
	private String lastName;	
	private String mobile;	
	private String emailId;	
	public ObjectId get_id() {
		return _id;
	}
	public void set_id(ObjectId _id) {
		this._id = _id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getEmailId() {
		return emailId;
	}
	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}
}

Create Rest API's to perform CRUD operations in MongoDB

Let's start to create the controller class with the rest APIs to perform CRUD operations. The below controller class is having four APIs for save profiles, get profile information, update profiles and delete profiles.

package com.tipstocode.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.tipstocode.manager.ProfileManager;
import com.tipstocode.model.ProfileVO;

@RestController
public class ProfileController {
	
	@Autowired
	ProfileManager userManager;	

	@RequestMapping(value = "/saveprofile", method = RequestMethod.POST )
	public ResponseEntity<ProfileVO> saveUser(@RequestBody ProfileVO userVO) {		
		userVO = userManager.saveUser(userVO);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);
		}	

	@RequestMapping(value = "/getprofilebyid", method = RequestMethod.GET )
	public ResponseEntity<ProfileVO> getUserById(@RequestParam("id") String id) {		
		ProfileVO userVO = userManager.getUserById(id);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);
		}	

	@RequestMapping(value = "/updateprofile", method = RequestMethod.POST )
	public ResponseEntity<ProfileVO> updateUser(@RequestBody ProfileVO userVO) {		
		userVO = userManager.updateUser(userVO);		
		return new ResponseEntity<ProfileVO>(userVO, HttpStatus.OK);
		}	

	@RequestMapping(value = "/deleteprofilebyid", method = RequestMethod.GET )
	public ResponseEntity<String> deleteUserById(@RequestParam("id") String id) {		
		String message = userManager.deleteUserById(id);		
		return ResponseEntity.ok(message);		
		}
}

Let's create the package called com.tipstocode.manager which contains the ProfileManager interface and ProfileManagerImpl class that implements the interface. Here we can do all the business logic.

package com.tipstocode.manager;
import com.tipstocode.model.ProfileVO;

public interface ProfileManager {
	ProfileVO saveUser(ProfileVO userVO);
	ProfileVO getUserById(String id);
	ProfileVO updateUser(ProfileVO userVO);
	String deleteUserById(String id);
}
package com.tipstocode.manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.tipstocode.dao.ProfileDAO;
import com.tipstocode.model.ProfileVO;

@Component
public class ProfileManagerImpl implements ProfileManager{	
	@Autowired	
	ProfileDAO userDAO;
	public ProfileVO saveUser(ProfileVO userVO) {
		// TODO Auto-generated method stub
		return userDAO.saveUser(userVO);
	}
	public ProfileVO getUserById(String id) {
		// TODO Auto-generated method stub
		return userDAO.getUserById(id);
	}
	public ProfileVO updateUser(ProfileVO userVO) {
		// TODO Auto-generated method stub
		return userDAO.updateUser(userVO);
	}
	public String deleteUserById(String id) {
		// TODO Auto-generated method stub		
		userDAO.deleteUserById(id);		
		return "Deleted Successfully!.";
	}
}

Let's create the package called com.tipstocode.dao which contains ProfileDAO interface and ProfileDAOImpl class that implements the interface. Here we can do all the Database logic like here we did save, edit, delete, and update.

package com.tipstocode.dao;
import com.tipstocode.model.ProfileVO;

public interface ProfileDAO {
	ProfileVO saveUser(ProfileVO userVO);
	ProfileVO getUserById(String id);
	ProfileVO updateUser(ProfileVO userVO);
	void deleteUserById(String id);
}
package com.tipstocode.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import com.tipstocode.model.ProfileVO;

@Repository
public class ProfileDAOImpl implements ProfileDAO{	
	@Autowired
	MongoTemplate mongoTemplate;
	public ProfileVO saveUser(ProfileVO userVO) {
		// TODO Auto-generated method stub
		return userVO = mongoTemplate.save(userVO);
	}
	public ProfileVO getUserById(String id) {
		// TODO Auto-generated method stub
		return mongoTemplate.findById(id, ProfileVO.class);
	}
	public ProfileVO updateUser(ProfileVO userVO) {
		// TODO Auto-generated method stub
		return userVO = mongoTemplate.save(userVO);
	}
	public void deleteUserById(String id) {
		// TODO Auto-generated method stub
		ProfileVO userVO = mongoTemplate.findById(id, ProfileVO.class);
		mongoTemplate.remove(userVO);
	}
}

Note that in the above DAO Implementation class I used the save() method for both save and update. Actually, the MongoDB save operation performs both if the record is having _id then it updates if not it saves the record.

Now successfully created the controllers to perform crud operations in MongoDB. If you want to do validation of bean please take a look at it here. Let's start to test the APIs one by one in Postman.

Save Profile

Method : POST, ContentType : applicaiton/json.

Save Profile Postman Screen Shot
Save Profile Postman Screen Shot

Spring Boot returns the record id in the format of object id like below.

"_id": {
"timestamp": 1596612490,
"date": "2020-08-05T07:28:10.000+00:00"
},

This is not the readable format and we can not send this from the client also. So we need to return the ObjectId as String format. For that do the below changes in the getter function of Profile Bean

public String get_id() {
return _id.toHexString();
}

Get Profile By Id

Method : GET, Param : id

Get Profile Postman Screen Shot
Get Profile Postman Screen Shot

Update Profile

Method : POST, ContentType : applicaiton/json.

Update Profile Postman Screen Shot
Update Profile Postman Screen Shot

Delete Profile

Method : GET, Param : id

Delete Profile Postman Screen Shot
Delete Profile Postman Screen Shot

Get the Full Source Code from GitHub

Leave a Reply

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