Saving Tasks
Saving a task means storing it as a row in the database. The repository save method stores the task and returns the saved copy.
Save one task
Save stores the task. It returns the saved copy.
Task saved = tasks.save(task);Answer with the saved task
The answer carries status 201. The body shows the saved fields.
return ResponseEntity.status(201).body(new TaskDto(saved.getTitle(), saved.isDone()));Example
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@RestController
public class TaskController {
record TaskDto(String title, boolean done) {
}
private final TaskRepository tasks;
public TaskController(TaskRepository tasks) {
this.tasks = tasks;
}
@PostMapping("/tasks")
public ResponseEntity<TaskDto> addTask(@RequestBody Task task) {
Task saved = tasks.save(task);
return ResponseEntity.status(201).body(new TaskDto(saved.getTitle(), saved.isDone()));
}
}
interface TaskRepository extends JpaRepository<Task, Long> {
}
@Entity
class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private boolean done;
public Task() {
}
public Task(String title, boolean done) {
this.title = title;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}Key points
- The repository save method stores one task.
- Save takes the task and returns the saved copy.
- JPA fills in the id when the row is saved.
- A POST route takes the task from the request body.
- The answer shows the saved title and done flag.
In this example, the TaskDto record holds a title and a done flag. The controller keeps the repository in a final field. The constructor takes the repository as a parameter. The route answers POST /tasks. The method reads the task from the request body. Save stores the task and returns the saved copy. The answer carries status 201 with the saved title and done flag. The repository and the entity follow the controller.
Note
The answer leaves the id out, so the body stays fixed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the repository save method return?