Photo Dto Mapper
Now that we have our photo service implementation ready, we need to create a Data Transfer Object (DTO) to represent photos in our REST API responses.
Understanding DTOs
A DTO is a simple object that carries data between processes, helping us separate our internal data model from what we expose to API consumers.
In our case, we want to expose only the photo URL and upload date, keeping internal details like file paths private.
Creating the Photo DTO
Let's start by creating a new package com.devtiro.restaurant.domain.dtos and implementing our PhotoDto class:
package com.devtiro.restaurant.domain.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PhotoDto {
private String url;
private LocalDateTime uploadDate;
}The @Data annotation from Lombok generates getters, setters, equals, hashCode, and toString methods.
The @Builder annotation enables the builder pattern for creating instances of our DTO.
Implementing the Photo Mapper
To convert between our Photo entity and PhotoDto, we'll use MapStruct, a code generation tool that makes mapping between Java beans simple.
Create a new package com.devtiro.restaurant.mappers and add the PhotoMapper interface:
package com.devtiro.restaurant.mappers;
import com.devtiro.restaurant.domain.dtos.PhotoDto;
import com.devtiro.restaurant.domain.entities.Photo;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface PhotoMapper {
PhotoDto toDto(Photo photo);
}The @Mapper annotation tells MapStruct to generate the implementation.
The componentModel = "spring" parameter makes the mapper available for dependency injection.
The unmappedTargetPolicy = ReportingPolicy.IGNORE setting tells MapStruct to ignore any fields that don't have a matching property in the target object.
Summary
- Created
PhotoDtoto represent photos in API responses - Used Lombok annotations to reduce boilerplate code in the DTO
- Implemented
PhotoMapperinterface using MapStruct - Set up automatic mapping between
PhotoandPhotoDto