Product
entity.Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- MongoDB installed and running
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
Step 1: Setting Up the Project
1.1 Create a Spring Boot Project
-
Open Spring Initializr:
- Go to Spring Initializr in your web browser.
-
Configure Project Metadata:
- Project: Maven Project
- Language: Java
- Spring Boot: Select the latest version of Spring Boot
- Group: com.example
- Artifact: spring-boot-mongodb-crud
- Name: spring-boot-mongodb-crud
- Description: Spring Boot CRUD example with MongoDB
- Package Name: com.example.springbootmongodbcrud
- Packaging: Jar
- Java Version: 17 (or your preferred version)
- Click
Next
.
-
Select Dependencies:
- On the
Dependencies
screen, select the dependencies you need. For a basic Spring Boot CRUD application, you can start with:- Spring Web
- Spring Data MongoDB
- Click
Next
.
- On the
-
Generate the Project:
- Click
Generate
to download the project zip file. - Extract the zip file to your desired location.
- Click
-
Open the Project in Your IDE:
- Open your IDE and import the project as a Maven project.
1.2 Project Structure
After importing the project, you will see the following structure in your IDE:
spring-boot-mongodb-crud
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── springbootmongodbcrud
│ │ │ ├── SpringBootMongodbCrudApplication.java
│ │ │ ├── controller
│ │ │ ├── model
│ │ │ ├── repository
│ │ │ └── service
│ ├── main
│ │ └── resources
│ │ ├── application.properties
│ └── test
│ └── java
│ └── com
│ └── example
│ └── springbootmongodbcrud
│ └── SpringBootMongodbCrudApplicationTests.java
└── pom.xml
Step 2: Configuring MongoDB
2.1 Start MongoDB
- Ensure your MongoDB server is running. If you installed MongoDB locally, you can start it by running the following command in your terminal:
mongod
2.2 Configure Spring Boot to Use MongoDB
Open the application.properties
file located in the src/main/resources
directory and add the following configuration:
# MongoDB Database configuration
spring.data.mongodb.uri=mongodb://localhost:27017/springbootdb
Step 3: Creating the Entity
3.1 Create the Product
Entity
In the model
package, create a new Java class named Product
:
package com.example.springbootmongodbcrud.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private String description;
private double price;
// Getters and Setters
public String getId() {
return id;
}
public void setId(String 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;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Step 4: Creating the Repository
4.1 Create the ProductRepository
Interface
In the repository
package, create a new Java interface named ProductRepository
:
package com.example.springbootmongodbcrud.repository;
import com.example.springbootmongodbcrud.model.Product;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends MongoRepository<Product, String> {
}
Step 5: Creating the Service
5.1 Create the ProductService
Interface
In the service
package, create a new Java interface named ProductService
:
package com.example.springbootmongodbcrud.service;
import com.example.springbootmongodbcrud.model.Product;
import java.util.List;
import java.util.Optional;
public interface ProductService {
List<Product> getAllProducts();
Optional<Product> getProductById(String id);
Product saveProduct(Product product);
Product updateProduct(Product product);
void deleteProduct(String id);
}
5.2 Implement the ProductService
Interface
In the service
package, create a new Java class named ProductServiceImpl
:
package com.example.springbootmongodbcrud.service;
import com.example.springbootmongodbcrud.model.Product;
import com.example.springbootmongodbcrud.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@Override
public Optional<Product> getProductById(String id) {
return productRepository.findById(id);
}
@Override
public Product saveProduct(Product product) {
return productRepository.save(product);
}
@Override
public Product updateProduct(Product product) {
return productRepository.save(product);
}
@Override
public void deleteProduct(String id) {
productRepository.deleteById(id);
}
}
Step 6: Creating the Controller
6.1 Create the ProductController
Class
In the controller
package, create a new Java class named ProductController
:
package com.example.springbootmongodbcrud.controller;
import com.example.springbootmongodbcrud.model.Product;
import com.example.springbootmongodbcrud.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable String id) {
Optional<Product> product = productService.getProductById(id);
return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable String id, @RequestBody Product productDetails) {
Optional<Product> productOptional = productService.getProductById(id);
if (productOptional.isPresent()) {
Product product = productOptional.get();
product.setName(productDetails.getName());
product.setDescription(productDetails.getDescription());
product.setPrice(productDetails.getPrice());
return ResponseEntity.ok(productService.updateProduct(product));
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable String id) {
Optional<Product> product = productService.getProductById(id);
if (product.isPresent()) {
productService.deleteProduct(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
Step 7: Running the Application
-
Run the Application:
- Open the
SpringBootMongodbCrudApplication
class in thesrc/main/java/com/example/springbootmongodbcrud
directory. - Click the green
Run
Button in your IDE or use the terminal to run the application:./mvnw spring-boot:run
- Open the
-
Verify the Application:
- Open your web browser or a tool like Postman and navigate to
http://localhost:8080/api/products
.
- Open your web browser or a tool like Postman and navigate to
You can now perform CRUD operations on the Product
entity using the following endpoints:
- GET
/api/products
: Get all products - GET `/api/products/{id}`: Get product by ID
- POST
/api/products
: Create a new product - PUT
/api/products/{id}
: Update an existing product - DELETE
/api/products/{id}
: Delete a product
Conclusion
In this tutorial, we have walked through the process of creating a Spring Boot CRUD application with MongoDB. We configured the project, set up MongoDB, created the necessary entities, repositories, services, and controllers, and tested the CRUD operations. This setup provides a solid foundation for developing more complex Spring Boot applications with MongoDB.
Comments
Post a Comment