Spring MVC CRUD Example
- In Spring MVC we can develop a simple CRUD application.
- Here we are using the JDBC template for Database interaction.
Create a table
- Create one table of Products manually in the PostgreSQL database with four fields i.e. id, name, quantity and price. Here ID is auto increase which is generated by the sequence.
Example:
SpringBootCrudExample2Application.Java
package com.quipoin.crud.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootCrudExample2Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudExample2Application.class, args);
}
}
Product.java
package com.quipoin.crud.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
public Product() {
super();
}
public Product(int id, String name, int quantity, double price) {
super();
this.id = id;
this.name = name;
this.quantity = quantity;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
pom.xml
<?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.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.quipoin</groupId>
<artifactId>spring-boot-crud-example-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-crud-example-2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ProductController.java
package com.quipoin.crud.example.controller;
import com.quipoin.crud.example.entity.Product;
import com.quipoin.crud.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ProductController {
@Autowired
private ProductService service;
@PostMapping("/addProduct")
public Product addProduct(@RequestBody Product product) {
return service.saveProduct(product);
}
@PostMapping("/addProducts")
public List<Product> addProducts(@RequestBody List<Product> products) {
return service.saveProducts(products);
}
@GetMapping("/products")
public List<Product> findAllProducts() {
return service.getProducts();
}
@GetMapping("/productById/{id}")
public Product findProductById(@PathVariable int id) {
return service.getProductById(id);
}
@GetMapping("/product/{name}")
public Product findProductByName(@PathVariable String name) {
return service.getProductByName(name);
}
@PutMapping("/update")
public Product updateProduct(@RequestBody Product product) {
return service.updateProduct(product);
}
@DeleteMapping("/delete/{id}")
public String deleteProduct(@PathVariable int id) {
return service.deleteProduct(id);
}
}
ProductRepository.Java
package com.quipoin.crud.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.quipoin.crud.example.entity.Product;
public interface ProductRepository extends JpaRepository<Product,Integer> {
Product findByName(String name);
}
ProductService.Java
package com.quipoin.crud.example.service;
import com.quipoin.crud.example.entity.Product;
import com.quipoin.crud.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public Product saveProduct(Product product) {
return repository.save(product);
}
public List<Product> saveProducts(List<Product> products) {
return repository.saveAll(products);
}
public List<Product> getProducts() {
return repository.findAll();
}
public Product getProductById(int id) {
return repository.findById(id).orElse(null);
}
public Product getProductByName(String name) {
return repository.findByName(name);
}
public String deleteProduct(int id) {
repository.deleteById(id);
return "product removed !! " + id;
}
public Product updateProduct(Product product) {
Product existingProduct = repository.findById(product.getId()).orElse(null);
existingProduct.setName(product.getName());
existingProduct.setQuantity(product.getQuantity());
existingProduct.setPrice(product.getPrice());
return repository.save(existingProduct);
}
}
Here's a breakdown of the components in your example:
- SpringBootCrudExample2Application.java: This is the main class annotated with @SpringBootApplication which serves as the entry point for your Spring Boot application.
- Product.java: This class represents the Product entity with fields like id, name, quantity, and price. It is annotated with @Entity to mark it as a JPA entity.
- pom.xml: This is the Maven Project Object Model (POM) file that defines the dependencies and configurations for your project, including Spring Boot, Spring Data JPA, PostgreSQL driver, and other necessary dependencies.
- ProductController.java: This class defines RESTful endpoints for performing CRUD operations on products. It is annotated with @RestController to indicate that it's a controller handling REST requests.
- ProductRepository.java: This is a Spring Data JPA repository interface that extends JpaRepository. It provides methods for performing CRUD operations on the Product entity.
- ProductService.java: This class contains business logic for handling CRUD operations on products. It is annotated with @Service to indicate that it's a service component.