Introduction

CRUD (Create, Read, Update, Delete) applications are common in software development. Spring Boot simplifies the process of building such applications. In this tutorial, we'll guide you through creating a CRUD application using Spring Boot, and we'll provide you with sample code for each operation.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • Java Development Kit (JDK) installed
  • An Integrated Development Environment (IDE) like Spring Tool Suite or IntelliJ IDEA
  • Basic knowledge of Spring Boot

Create a New Spring Boot Project

Let's start by creating a new Spring Boot project:

  1. Open your IDE and select "File" > "New" > "Project..."
  2. Choose "Spring Initializr" or "Spring Boot" as the project type.
  3. Configure your project settings, such as the project name, package, and dependencies. For a CRUD application, you might need dependencies like "Spring Web," "Spring Data JPA," and a database driver (e.g., H2, MySQL).
  4. Click "Finish" to create the project.

Sample Code: Creating, Reading, Updating, and Deleting Data

We'll create a simple CRUD application for managing a list of tasks. Here's a sample code for creating, reading, updating, and deleting tasks:

// Task.java
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private boolean completed;
// Getters and setters
}
// TaskRepository.java
public interface TaskRepository extends JpaRepository<Task, Long> {
}
// TaskController.java
@RestController
@RequestMapping("/tasks")
public class TaskController {
@Autowired
private TaskRepository taskRepository;
@PostMapping
public Task createTask(@RequestBody Task task) {
return taskRepository.save(task);
}
@GetMapping
public List<Task> getTasks() {
return taskRepository.findAll();
}
@GetMapping("/{id}")
public Task getTask(@PathVariable Long id) {
return taskRepository.findById(id).orElse(null);
}
@PutMapping("/{id}")
public Task updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
return taskRepository.findById(id)
.map(task -> {
task.setTitle(updatedTask.getTitle());
task.setCompleted(updatedTask.isCompleted());
return taskRepository.save(task);
})
.orElse(null);
}
@DeleteMapping("/{id}")
public void deleteTask(@PathVariable Long id) {
taskRepository.deleteById(id);
}
}

This code defines an entity class (Task), a repository (TaskRepository), and a REST controller (TaskController) that handles CRUD operations for tasks. You can test these operations using API requests.


Conclusion

Building a CRUD application with Spring Boot is made easier with its powerful features and abstractions. This tutorial has covered the basics, and you can extend this example to build more complex applications.