映射结构:基于判别器字段抽象目标类和具体类型



MapStruct是否可以根据鉴别器属性确定抽象类/接口的具体类型?

假设一个目标抽象类CarEntity,有两个子类SUVCity,一个源类CarDto,有一个鉴别器字段type有两个枚举常量SUVCITY。你如何告诉 MapStruct 根据源类中鉴别器字段的值选择具体类?

方法签名通常为:

public abstract CarEntity entity2Dto(CarDto dto);

编辑

精度:CarDto没有任何子类。

如果我理解正确,这目前是不可能的。见#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);
}

最新更新