📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Learn Spring boot at https://www.javaguides.net/p/spring-boot-tutorial.html.
Setup MongoDB
Tools and technologies used
- Spring Boot - 3+
- Spring Framework - 6+
- MongoDB - 3.8.2
- JDK - 17 or later
- Maven - 3.5.1
- IDE - STS/Eclipse
Development Steps
1. Create a Spring Boot Application
2. The pom.xml File - Define Maven Dependencies
<?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>3.0.4</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<groupId>net.springboot.javaguides</groupId>
<artifactId>springboot-mongodb-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-thymeleaf-web-app</name>
<description>Demo project for Spring Boot + Mongo DB CRUD Example
</description>
<properties>
<java.version>17</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-validation</artifactId>
</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>
3. Project Structure
4. Configuring MongoDB database
# MONGODB (MongoProperties)
spring.data.mongodb.uri=mongodb://localhost:27017/ProductDB
use ProductDB
5. Creating the Product Model
package net.springboot.javaguides.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "ProductDB")
public class Product {
@Id
private long id;
@NotBlank
@Size(max = 100)
@Indexed(unique = true)
private String name;
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
6. Create a Spring Data Repository - ProductRepository.java
package net.springboot.javaguides.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import net.springboot.javaguides.model.Product;
public interface ProductRepository extends MongoRepository < Product, Long > {
}
7. Service Layer (uses repository)
ProductService.java
package net.springboot.javaguides.service;
import java.util.List;
import net.springboot.javaguides.model.Product;
public interface ProductService {
Product createProduct(Product product);
Product updateProduct(Product product);
List < Product > getAllProduct();
Product getProductById(long productId);
void deleteProduct(long id);
}
ProductServiceImpl.java
package net.springboot.javaguides.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import net.springboot.javaguides.exception.ResourceNotFoundException;
import net.springboot.javaguides.model.Product;
import net.springboot.javaguides.repository.ProductRepository;
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public Product createProduct(Product product) {
return productRepository.save(product);
}
@Override
public Product updateProduct(Product product) {
Optional < Product > productDb = this.productRepository.findById(product.getId());
if (productDb.isPresent()) {
Product productUpdate = productDb.get();
productUpdate.setId(product.getId());
productUpdate.setName(product.getName());
productUpdate.setDescription(product.getDescription());
productRepository.save(productUpdate);
return productUpdate;
} else {
throw new ResourceNotFoundException("Record not found with id : " + product.getId());
}
}
@Override
public List < Product > getAllProduct() {
return this.productRepository.findAll();
}
@Override
public Product getProductById(long productId) {
Optional < Product > productDb = this.productRepository.findById(productId);
if (productDb.isPresent()) {
return productDb.get();
} else {
throw new ResourceNotFoundException("Record not found with id : " + productId);
}
}
@Override
public void deleteProduct(long productId) {
Optional < Product > productDb = this.productRepository.findById(productId);
if (productDb.isPresent()) {
this.productRepository.delete(productDb.get());
} else {
throw new ResourceNotFoundException("Record not found with id : " + productId);
}
}
}
8. Creating the APIs - ProductController
package net.springboot.javaguides.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import net.springboot.javaguides.model.Product;
import net.springboot.javaguides.service.ProductService;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/products")
public ResponseEntity < List < Product >> getAllProduct() {
return ResponseEntity.ok().body(productService.getAllProduct());
}
@GetMapping("/products/{id}")
public ResponseEntity < Product > getProductById(@PathVariable long id) {
return ResponseEntity.ok().body(productService.getProductById(id));
}
@PostMapping("/products")
public ResponseEntity < Product > createProduct(@RequestBody Product product) {
return ResponseEntity.ok().body(this.productService.createProduct(product));
}
@PutMapping("/products/{id}")
public ResponseEntity < Product > updateProduct(@PathVariable long id, @RequestBody Product product) {
product.setId(id);
return ResponseEntity.ok().body(this.productService.updateProduct(product));
}
@DeleteMapping("/products/{id}")
public HttpStatus deleteProduct(@PathVariable long id) {
this.productService.deleteProduct(id);
return HttpStatus.OK;
}
}
ResourceNotFoundException
package net.springboot.javaguides.exception;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1 L;
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
}
Running Spring boot application
package net.springboot.javaguides;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Test REST APIs Using Postman Client
Create Product Rest API - Post HTTP Request
Update Product Rest API - PUT HTTP Request
Delete Product Rest API - Delete HTTP Request
Get Product Rest API - Get HTTP Request
Get All Product Rest API - Get HTTP Request
GitHub Repository
Download source code of this tutorial from my GitHub repository at https://github.com/RameshMF/spring-boot-tutorial.
Nice tutorial, simple and explanatory. Thanks Ramesh!
ReplyDelete