简体   繁体   中英

Mapstruct : abstract target class and concrete type based on discriminator field

Is it possible with MapStruct to determine the concrete type of an abstract class / interface based on a discriminator property ?

Imagine a target abstract class CarEntity with two subclasses SUV and City and a source class CarDto with a discriminator field type with two enumeration constants SUV and CITY . How do you tell MapStruct to choose the concrete class based on the value of the discriminator field in the source class ?

Method signature would typically be :

public abstract CarEntity entity2Dto(CarDto dto);

EDIT

precision : CarDto doesn't have any subclasses.

If I understood correctly this is currently not possible. See #131 .

A way to achieve what you need would be to do something like:

@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);
}

Instead of doing instance of checks. You can use the discriminator field.

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM