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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With