Mapstruct:基于鉴别器字段的抽象目标类和具体类型

Tho*_*ali 5 java mapstruct

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

想象一个CarEntity具有两个子类SUVand的目标抽象类City和一个带有两个枚举常量andCarDto的鉴别器字段的源类。你如何告诉 MapStruct 根据源类中鉴别器字段的值选择具体类?typeSUVCITY

方法签名通常是:

public abstract CarEntity entity2Dto(CarDto dto);
Run Code Online (Sandbox Code Playgroud)

编辑

精度:CarDto没有任何子类。

Fil*_*lip 6

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

而不是做检查实例。您可以使用鉴别器字段。

@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);
}
Run Code Online (Sandbox Code Playgroud)