Spring Boot MongoDB CRUD Example

Spring Mongo CRUD

Here you will see a post on Spring Boot MongoDB CRUD example, where CRUD means Create, Read, Update, and Delete operations. For performing CRUD operations on MongoDB through Spring Boot framework, you need to add required dependency. I will use Spring REST controller to publish the MongoDB CRUD operations using REST or RESTful API.

Related Posts:

Prerequisites

Java 8/19, Gradle 5.4.1, Maven 3.8.5, Spring Boot 2.1.6/3.1.5

Installing MongoDB in Windows

Project Setup

For spring boot 3.x I am going to use the pom.xml file with required configurations for the project:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-boot-mongodb-crud</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>19</maven.compiler.source>
		<maven.compiler.target>19</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.5</version>
	</parent>

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

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

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

The build.gradle script is used for spring boot 2.x version to include required dependencies.

buildscript {
	ext {
		springBootVersion = '2.1.6.RELEASE'
	}
    repositories {
    	mavenLocal()
    	mavenCentral()
    }
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
	mavenLocal()
    mavenCentral()
}
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	compile("org.springframework.boot:spring-boot-starter-data-mongodb:${springBootVersion}")
}

MongoDB Config

As I have mentioned in the prerequisites section, you need to go through Installing MongoDB in Windows to install MongoDB and create database roytuts into it.

If you do not specify anything in the application.properties or application.yml file then Spring Boot, by default, connects to test database of Mongo server at localhost:27017.

Here I will specify our roytuts database for connecting to it.

Notice also I have mentioned spring.jackson.default-property-inclusion=NON_NULL to ignore null field in JSON response.

Create below content into src/main/resources/application.properties file.

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=roytuts
spring.jackson.default-property-inclusion=NON_NULL

Entity Class

I will connect with database, where I will perform CRUD operations. Therefore I need to create entity class to map out database column with Java class attributes.

I want to store user details, such as, id, name, email and password of the user.

Another beauty of Spring Boot Data MongoDB starter is the below class will create the required collection in the database. Even I didn’t mention any column name, so it will create same column name in the table as the Java attributes.

So the corresponding user entity class can be defined as:

public class User {

	@Id
	private String id;
	private String name;
	private String email;
	private String pwd;

	//getters and setters

}

VO Class

It is always good idea to create a VO or DTO class to return as a response object from REST controller instead of returning the entity class as a response object.

The VO class is also similar to the above entity class.

public class UserVo {

	private String id;
	private String name;
	private String email;
	private String pwd;

	//getters and setters

}

Repository Interface

Spring Data MongoDB provides built-in methods for performing basic CRUD operations and you don’t need to write any query method.

Another beauty of Spring Data MongoDB is that you write Java method to query your database and Spring generates the corresponding query from your method for performing database operations.

I have just extended the MongoRepository interface but I did not write any query method inside this repository because I will use Spring’s built-in methods for performing CRUD operations.

public interface UserRepository extends MongoRepository<User, String> {
}

Service Class

The service class is used generally if you want to perform some business logic or conversion to different data.

Here in the below service method I will convert entity class to VO class using Java 8’s stream API.

I have used Java 8’s map() method to map entity to VO object.

@Service
public class UserService {

	@Autowired
	private UserRepository repository;

	public List<UserVo> getUserList() {
		return repository.findAll().stream().map(u -> {
			UserVo vo = new UserVo();
			vo.setId(u.getId());
			vo.setName(u.getName());
			vo.setEmail(u.getEmail());
			return vo;
		}).collect(Collectors.toList());
	}

	public UserVo getUserById(String id) {
		return repository.findById(id).map(u -> {
			UserVo vo = new UserVo();
			vo.setId(u.getId());
			vo.setName(u.getName());
			vo.setEmail(u.getEmail());
			return vo;
		}).orElse(null);
	}

	public void saveUser(UserVo vo) {
		User user = new User();
		user.setName(vo.getName());
		user.setEmail(vo.getEmail());
		user.setPwd(vo.getPwd());
		repository.save(user);
	}

	public void updateUser(UserVo vo) {
		User user = new User();
		user.setId(vo.getId());
		user.setName(vo.getName());
		user.setEmail(vo.getEmail());
		user.setPwd(vo.getPwd());
		repository.save(user);
	}

	public void deleteUser(UserVo vo) {
		User user = new User();
		user.setId(vo.getId());
		repository.delete(user);
	}

}

REST Controller

Now I will expose our CRUD operations onto REST API so that any client can call our REST service and perform CRUD operations.

Exposing the operations on REST makes loosely coupled to integrate with any client technologies.

Notice how I have performed CRUD operations using the same endpoint with different HTTP methods.

@RestController
public class UserRestController {

	@Autowired
	private UserService service;

	@GetMapping("/user/{id}")
	public ResponseEntity<UserVo> getUser(@PathVariable String id) {
		return new ResponseEntity<>(service.getUserById(id), HttpStatus.OK);
	}

	@GetMapping("/user")
	public ResponseEntity<List<UserVo>> getUserList() {
		return new ResponseEntity<>(service.getUserList(), HttpStatus.OK);
	}

	@PostMapping("/user")
	public ResponseEntity<String> saveUser(@RequestBody UserVo UserVo) {
		service.saveUser(UserVo);
		return new ResponseEntity<>("New user successfully saved", HttpStatus.OK);
	}

	@PutMapping("/user")
	public ResponseEntity<String> updateUser(@RequestBody UserVo UserVo) {
		service.updateUser(UserVo);
		return new ResponseEntity<>("User successfully updated", HttpStatus.OK);
	}

	@DeleteMapping("/user")
	public ResponseEntity<String> deleteUser(@RequestBody UserVo userVo) {
		service.deleteUser(userVo);
		return new ResponseEntity<>("User successfully deleted", HttpStatus.OK);
	}

}

Main Class

Creating a main would be sufficient to deploy our application into the Tomcat server. This is a great advantage that you just need to let Spring know that it is your Spring Boot Application using @SpringBootApplication and main class.

I also need to tell Spring where our entity class and repository interface.

@SpringBootApplication
@EntityScan("com.roytuts.spring.boot.mongodb.crud.entity")
@EnableMongoRepositories("com.roytuts.spring.boot.mongodb.crud.repository")
public class SpringMongoDbJpaCrudApp {

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

}

Running the Spring Mongo Application

Run the main class to start the application. The application will start on embedded Tomcat server’s port 8080.

Testing the Spring Mongo Application

As you know that you don’t have any data into the database so you will first create a new user and store into database.

Create a user

Request Method: POST

Request URL: http://localhost:8080/user

Request Body:

{
	"name":"Soumitra",
	"email":"contact@roytuts.com",
	"pwd":"pwd"
}

Response: New user successfully saved

Read User

Read All Users

Request Method: GET

Request URL: http://localhost:8080/user

Response:

Array[1]
	0: {
	"id": "5d1c88a45ed21a532cb07a46",
	"name": "Soumitra",
	"email": "contact@roytuts.com"
	}
]

Read Single User

Request Method: GET

Request URL: http://localhost:8080/user/5d1c88a45ed21a532cb07a46

Response:

{
	"id": "5d1c88a45ed21a532cb07a46",
	"name": "Soumitra",
	"email": "contact@roytuts.com"
}

Update User

Request Method: PUT

Request URL: http://localhost:8080/user

Request Body:

{
    "id": "5d1c88a45ed21a532cb07a46",
	"name":"Soumitra Roy",
	"email":"contact@roytuts.com",
	"pwd":"pwd"
}

Response: User successfully updated

Verify Update

Request Method: GET

Request URL: http://localhost:8080/user

Response:

Array[1]
	0: {
	"id": "5d1c88a45ed21a532cb07a46",
	"name": "Soumitra Roy",
	"email": "contact@roytuts.com"
	}
]

Delete User

Request Method: DELETE

Request URL: http://localhost:8080/user

Request Body:

{
    "id": "5d1c88a45ed21a532cb07a46"
}

Response: User successfully deleted

That’s all. Hope you got idea on Spring Boot MongoDB CRUD Example.

Source Code

Download

Leave a Reply

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