Restaurant Search Dto Mappers
When displaying search results, we want to return only the data that's needed for the search results view, so let's created dedicated DTOs for this now.
Creating the Summary DTO
Let's create a streamlined version of our restaurant DTO specifically for search results:
package com.devtiro.restaurant.domain.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RestaurantSummaryDto {
private String id;
private String name;
private String cuisineType;
private Float averageRating;
private Integer totalReviews;
private AddressDto address;
private List<PhotoDto> photos;
}Notice how this DTO includes only the fields needed for search results, omitting detailed information like full descriptions, opening hours, or contact details.
Updating the Restaurant Mapper
Now we need to add mapping support for our new summary DTO:
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface RestaurantMapper {
// ...
@Mapping(source = "reviews", target = "totalReviews", qualifiedByName = "populateTotalReviews")
RestaurantSummaryDto toSummaryDto(Restaurant restaurant);
@Named("populateTotalReviews")
default Integer populateTotalReviews(List<Review> reviews) {
return reviews.size();
}
}MapStruct will automatically implement the toSummaryDto method, matching fields between the Restaurant entity and our new RestaurantSummaryDto.
We implement the method populateTotalReviews to tell MapStruct how to populate this field.
Summary
- Created
RestaurantSummaryDtofor lightweight search results - Added
toSummaryDtoandpopulateTotalReviewsmapping methods toRestaurantMapper