In this tutorial, we will take a look at how to use MongoDB as a database for your Spring Boot Application.
In software development, using a NoSQL database like MongoDB can provide flexibility and scalability for applications that deal with large amounts of unstructured or semi-structured data.
MongoDB is a popular document-oriented NoSQL database that can be easily integrated with Java applications.
For this tutorial, we will use MongoDB as our primary database. We'll keep the application simple so that it's easy to understand the concept of working with MongoDB in a Spring Boot application.
Step 1: MongoDB configuration
applications.properties
#MongoDB
spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
spring.data.mongodb.database=mydatabase
Note: Make sure you have MongoDB installed and running on your local machine, or update the URI to point to your MongoDB instance.
Gradle Configuration
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.6'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.jetbrains:annotations:23.0.0'
}
tasks.named('test') {
useJUnitPlatform()
}
Step 2: Our Entity
Keeping it really simple with id, userId and userName fields.
package com.example.mongodemo;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "users")
public class User {
@Id
private String id;
private int userId;
private String userName;
public User(int userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Step 3: Spring Data MongoDB Repository for User
package com.example.mongodemo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends MongoRepository {
Optional findByUserId(Integer userId);
void deleteByUserId(Integer userId);
}
Step 4: User Service class
package com.example.mongodemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public Optional findUserByUserId(Integer userId) {
System.out.println("User fetched from MongoDB!");
return userRepository.findByUserId(userId);
}
public User save(User user) {
return userRepository.save(user);
}
public void updateUser(Integer userId, String userName) {
userRepository.findByUserId(userId).ifPresent(user -> {
user.setUserName(userName);
userRepository.save(user);
});
}
public void deleteUserByUserId(Integer userId) {
userRepository.deleteByUserId(userId);
}
}
Step 5: User Controller
package com.example.mongodemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping(path = "/get-user/{userId}")
public Optional getUserName(@PathVariable("userId") int userId) {
return userService.findUserByUserId(userId);
}
@PostMapping(path = "/add-user")
public void addUser(@RequestBody User user) {
System.out.println("User Saved!");
userService.save(user);
}
@PostMapping(path = "/update-user")
public void updateUser(@RequestBody User user) {
System.out.println("User Updated!");
userService.updateUser(user.getUserId(), user.getUserName());
}
@DeleteMapping(path = "/delete-user/{userId}")
public void deleteUser(@PathVariable("userId") int userId) {
System.out.println("User Deleted!");
userService.deleteUserByUserId(userId);
}
}
As you may see, we have performed all CRUD operations using Spring Data MongoDB, integrating MongoDB as our primary database for the Spring Boot application.
CRUD Operations cURL Commands
Create User:
curl --location 'http://localhost:8080/add-user' \ --header 'Content-Type: application/json' \ --data '{ "userId": 10, "userName": "Harry" }'
Retrieve User:
curl --location 'http://localhost:8080/get-user/10' \ --header 'Content-Type: application/json'
Update User:
curl --location 'http://localhost:8080/update-user' \ --header 'Content-Type: application/json' \ --data '{ "userId":10, "userName":"Ron" }'
Delete User:
curl --location --request DELETE 'http://localhost:8080/delete-user/10'
Facing issues? Have Questions? Post them here! I am happy to answer!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- How to know Roblox Version Details on Mac - MacOS
- How to Parse XML String in Python - Python
- Share Image and Text on Instagram from Android App using Share Dialog - Android
- Meaning of javascript:void(0) explained with example - JavaScript
- SharePoint CAML query error - The XML source is not correct - SharePoint
- MongoDB Group By and Count Examples - Article
- Fix - JioCinema Something Went Wrong Please Try Again Error 8001 while streaming IPL Cricket Live - HowTos
- Git: Delete Branch Locally and Remotely at Origin - Git