Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-08-07 13:10:19 Viewed : 700
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".
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).
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.
javaimport 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
}
javaimport org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}
javaimport 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 taskRepository.save(task);
}
public Task updateTask(Task task) {
return taskRepository.save(task);
}
public void deleteTask(Long id) {
taskRepository.deleteById(id);
}
}
javaimport 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 task.map(value -> 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);
}
}
application.properties
or application.yml
file, depending on your preference and database choice.Example application.properties
for H2 in-memory database:
propertiesspring.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
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.