Create Task Dto
Now that we have our Task and TaskList entities set up, we need to create Data Transfer Objects (DTOs) to represent these entities in our REST API. DTOs help us separate our domain model from our API contract and give us control over what data we expose to clients.
Let's start with the TaskDto class. We'll use a Java record for this as it provides a concise way to create an immutable data class with all the boilerplate code we need.
First, let's create a new package com.devtiro.tasks.domain.dto to hold our DTOs. Then create a new record called TaskDto:
package com.devtiro.tasks.domain.dto;
import com.devtiro.tasks.domain.entities.TaskPriority;
import com.devtiro.tasks.domain.entities.TaskStatus;
import java.time.LocalDateTime;
import java.util.UUID;
public record TaskDto(
UUID id,
String title,
String description,
LocalDateTime dueDate,
TaskPriority priority,
TaskStatus status
) { }Let's break down what we've included in our TaskDto:
id- The UUID identifier of the tasktitle- The task's titledescription- The task's descriptiondueDate- When the task is duepriority- The task's priority (HIGH, MEDIUM, LOW)status- The task's status (OPEN, CLOSED)
Notice what we've left out compared to our Task entity:
- No
createdorupdatedtimestamps - these are internal concerns - No
taskListreference - we'll handle this relationship through URLs in our REST API - No JPA annotations - DTOs are simple data carriers
By using a record, Java automatically provides us with:
- Constructor for all fields
- Getter methods (using the component names)
- equals() and hashCode() methods
- toString() method
- Immutability (all fields are final)
We can now use this DTO to:
- Accept task data from API requests
- Return task data in API responses
- Transfer task data between layers of our application
Summary
- Created the
TaskDtorecord to represent tasks in our API - Included only the fields needed for the API contract
- Used Java records for automatic getter methods and immutability
- Excluded internal implementation details like timestamps and JPA relationships