我在 Spring Boot 中创建 Rest API
public class Garage {
private Integer id;
private String address;
private Integer numberOfSpaces;
private boolean accessLpg;
private double width;
我也有
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
}
我需要在车库中返回附加信息,例如 FreeSpots 和 BusySpots(已经有汽车实体)
如何添加此信息?我需要其他课程还是可以将其添加到 GarageDTO 中?或者我需要映射器?
有人可以帮助我吗?
我尝试过这样的事情
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();
}
}
但我认为这不是一个好的解决方案
我认为Mapstruct或类似的映射库可以帮助你。
在Mapstruct中查看@Mapping或@AfterMapping中的defaultExpression