I create Rest API in spring boot
public class Garage {
private Integer id;
private String address;
private Integer numberOfSpaces;
private boolean accessLpg;
private double width;
also I have
public class GarageDto {
private Integer id;
private String address;
private Integer numberOfSpaces;
private boolean accessLpg;
private double width;
public static GarageDto fromEntity(Garage garage) {
//INSIDE METHOD TO MAPPING FROM ENTITY TO DTO
}
I need return additional information in Garage like FreeSpots and BusySpots (Already have also car entity)
How to add this information ? I need other class or can I add this to GarageDTO ? or I need Mapper ?
Can someone help me ?
I tried something like this
public class GarageDto {
private Integer id;
private String address;
private Integer numberOfSpaces;
private boolean accessLpg;
private double width;
private int freeSpaces;
private int busySpaces;
public static GarageDto fromEntity(Garage garage) {
GarageDtoBuilder builder = GarageDto.builder()
.id(garage.getId())
.address(garage.getAddress())
.numberOfSpaces(garage.getNumberOfSpaces())
.accessLpg(garage.isAccessLpg())
.width(garage.getWidth());
if (garage.getCars() != null) {
builder.freeSpaces(garage.getNumberOfSpaces() - garage.getCars().size())
.busySpaces(garage.getCars().size());
} else {
builder.freeSpaces(garage.getNumberOfSpaces())
.busySpaces(0);
}
return builder.build();
}
}
but I thinking its not good solution
I think Mapstruct or similar mapping libraries can help you.
In Mapstruct see defaultExpression in @Mapping or @AfterMapping.
GarageMapper.java:
ExampleService.java:
Output: