Mapstruct : 抽象目标 class 和基于鉴别器字段的具体类型
Mapstruct : abstract target class and concrete type based on discriminator field
MapStruct 是否可以根据鉴别器 属性 确定抽象 class / 接口的具体类型?
想象一个目标抽象 class CarEntity
有两个子 class es SUV
和 City
和一个源 class CarDto
带有一个鉴别器字段 type
和两个枚举常量 SUV
和 CITY
。您如何告诉 MapStruct 根据源 class 中鉴别器字段的值选择具体的 class?
方法签名通常是:
public abstract CarEntity entity2Dto(CarDto dto);
编辑
精度 : CarDto
没有任何子classes.
如果我理解正确的话,目前这是不可能的。参见 #131。
实现您所需的一种方法是执行以下操作:
@Mapper
public interface MyMapper {
default CarEntity entity2Dto(CarDto dto) {
if (dto == null) {
return null;
} else if (dto instance of SuvDto) {
return fromSuv((SuvDto) dto));
} //You need to add the rest
}
SuvEntity fromSuv(SuvDto dto);
}
而不是做检查实例。您可以使用鉴别器字段。
@Mapper
public interface MyMapper {
default CarEntity entity2Dto(CarDto dto) {
if (dto == null) {
return null;
} else if (Objects.equals(dto.getDiscriminator(), "suv")) {
return fromSuv(dto));
} //You need to add the rest
}
SuvEntity fromSuv(CarDto dto);
}
MapStruct 是否可以根据鉴别器 属性 确定抽象 class / 接口的具体类型?
想象一个目标抽象 class CarEntity
有两个子 class es SUV
和 City
和一个源 class CarDto
带有一个鉴别器字段 type
和两个枚举常量 SUV
和 CITY
。您如何告诉 MapStruct 根据源 class 中鉴别器字段的值选择具体的 class?
方法签名通常是:
public abstract CarEntity entity2Dto(CarDto dto);
编辑
精度 : CarDto
没有任何子classes.
如果我理解正确的话,目前这是不可能的。参见 #131。
实现您所需的一种方法是执行以下操作:
@Mapper
public interface MyMapper {
default CarEntity entity2Dto(CarDto dto) {
if (dto == null) {
return null;
} else if (dto instance of SuvDto) {
return fromSuv((SuvDto) dto));
} //You need to add the rest
}
SuvEntity fromSuv(SuvDto dto);
}
而不是做检查实例。您可以使用鉴别器字段。
@Mapper
public interface MyMapper {
default CarEntity entity2Dto(CarDto dto) {
if (dto == null) {
return null;
} else if (Objects.equals(dto.getDiscriminator(), "suv")) {
return fromSuv(dto));
} //You need to add the rest
}
SuvEntity fromSuv(CarDto dto);
}