Performing CRUD (Create, Read, Update, Delete) operations using Spring Boot and JPA (Java Persistence API).

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-08-07 13:10:19 Viewed : 309

Performing CRUD (Create, Read, Update, Delete) operations using Spring Boot and JPA (Java Persistence API).

Provide you with a simple example of performing CRUD (Create, Read, Update, Delete) operations using Spring Boot and JPA (Java Persistence API). In this example, we will create a basic application to manage a list of "tasks".

  1. Project Setup: Create a new Spring Boot project using your preferred IDE or Spring Initializr. Add the following dependencies: "Spring Web", "Spring Data JPA", and your preferred database driver (e.g., H2 for an in-memory database or MySQL for a real database).

  2. Task Entity: Create an entity class for the "Task" with the necessary annotations for JPA mapping. This class will represent the data you want to store in the database.

import javax.persistence.*; @Entity @Table(name = "tasks") public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private boolean completed; // getters and setters }
  1. Task Repository: Create a JPA repository interface to perform database operations on the "Task" entity.
import; import org.springframework.stereotype.Repository; @Repository public interface TaskRepository extends JpaRepository<Task, Long> { }
  1. Service Layer: Create a service class to encapsulate business logic. Here, we will define methods for creating, reading, updating, and deleting tasks.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class TaskService { private final TaskRepository taskRepository; @Autowired public TaskService(TaskRepository taskRepository) { this.taskRepository = taskRepository; } public List<Task> getAllTasks() { return taskRepository.findAll(); } public Optional<Task> getTaskById(Long id) { return taskRepository.findById(id); } public Task createTask(Task task) { return; } public Task updateTask(Task task) { return; } public void deleteTask(Long id) { taskRepository.deleteById(id); } }
  1. Controller: Create a REST controller to handle incoming HTTP requests and interact with the service layer.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/tasks") public class TaskController { private final TaskService taskService; @Autowired public TaskController(TaskService taskService) { this.taskService = taskService; } @GetMapping public List<Task> getAllTasks() { return taskService.getAllTasks(); } @GetMapping("/{id}") public ResponseEntity<Task> getTaskById(@PathVariable Long id) { Optional<Task> task = taskService.getTaskById(id); return -> new ResponseEntity<>(value, HttpStatus.OK)) .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PostMapping public Task createTask(@RequestBody Task task) { return taskService.createTask(task); } @PutMapping("/{id}") public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task task) { if (!taskService.getTaskById(id).isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } task.setId(id); return new ResponseEntity<>(taskService.updateTask(task), HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteTask(@PathVariable Long id) { if (!taskService.getTaskById(id).isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } taskService.deleteTask(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
  1. Application Properties: Configure your database connection settings in the or application.yml file, depending on your preference and database choice.

Example for H2 in-memory database:

spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true spring.jpa.hibernate.ddl-auto=update
  1. Run the Application: Run your Spring Boot application. You can access the H2 database console by visiting http://localhost:8080/h2-console (if you have configured H2) and the REST endpoints at http://localhost:8080/tasks.

Remember, this example is meant to illustrate the basic concepts of performing CRUD operations using Spring Boot and JPA. In a real-world application, you might want to add validation, error handling, security, and other features to make your application more robust.

Related Articles

Leave a Comment: