Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mapstruct

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.

like image 297
Thomas Naskali Avatar asked Jun 01 '18 12:06

Thomas Naskali


1 Answers

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);
}
like image 100
Filip Avatar answered Oct 25 '22 14:10

Filip