springboot-module-3/
├── src/
│ └── main/
│ ├── java/
│ │ └── com.example.module3/
│ │ ├── controller/
│ │ │ └── TaskController.java
│ │ ├── model/
│ │ │ └── Task.java
│ │ └── SpringBootModule3Application.java
│ └── resources/
│ └── application.properties
├── README.md
└── pom.xml
Created
April 23, 2025 17:07
-
-
Save kavicastelo/32a75d6f15e393ac329254c33ee958d5 to your computer and use it in GitHub Desktop.
Spring Boot Learning Module 3 – Simple In-Memory CRUD API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Task { | |
| private Long id; | |
| @NotBlank(message = "Title is required") | |
| private String title; | |
| private boolean completed = false; | |
| // constructor, getters, setters | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @RestController | |
| @RequestMapping("/api/tasks") | |
| public class TaskController { | |
| private List<Task> tasks = new ArrayList<>(); | |
| private AtomicLong idGenerator = new AtomicLong(); | |
| @PostMapping | |
| public ResponseEntity<Task> createTask(@Valid @RequestBody Task task) { | |
| task.setId(idGenerator.incrementAndGet()); | |
| tasks.add(task); | |
| return ResponseEntity.status(HttpStatus.CREATED).body(task); | |
| } | |
| @GetMapping | |
| public List<Task> getAllTasks() { | |
| return tasks; | |
| } | |
| @GetMapping("/{id}") | |
| public ResponseEntity<Task> getTask(@PathVariable Long id) { | |
| return tasks.stream() | |
| .filter(t -> t.getId().equals(id)) | |
| .findFirst() | |
| .map(ResponseEntity::ok) | |
| .orElse(ResponseEntity.notFound().build()); | |
| } | |
| @PutMapping("/{id}") | |
| public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task updatedTask) { | |
| for (Task task : tasks) { | |
| if (task.getId().equals(id)) { | |
| task.setTitle(updatedTask.getTitle()); | |
| task.setCompleted(updatedTask.isCompleted()); | |
| return ResponseEntity.ok(task); | |
| } | |
| } | |
| return ResponseEntity.notFound().build(); | |
| } | |
| @DeleteMapping("/{id}") | |
| public ResponseEntity<Void> deleteTask(@PathVariable Long id) { | |
| boolean removed = tasks.removeIf(t -> t.getId().equals(id)); | |
| return removed ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment