I´ve being looking in SO for this question but can´t find an answer.
I would like to know if there is a way to map from multiple Entity´s fields to single DTO but with another mapper and into an encapsulated DTO.
An example:
This is my entity:
public class Identification{
long dbId;
String id;
String type;
String completeName;
boolean status;
}
My DTO:
public class PersonEntity{
String completeName;
IdentificationEntity identificationEntity;
}
public class IdentificationEntity{
String documentNumber;
boolean status;
String documentType;
}
I Created my mapper:
@Mapper(componentModel = "spring", uses = {IdentificationMapper.class})
public interface PersonMapper {
PersonEntity toPersonEntity(Identification identification);
}
@Mapper(componentModel = "spring")
public interface IdentificationMapper {
@Mapping(source = "id", target = "documentNumber")
@Mapping(source = "type", target = "documentType")
IdentificationEntity toIdentificationEntity(Identification identification);
}
but i don't know how to map the IdentificationEntity from PersonEntity with a mapper. What I mean is if there is a way without using @AfterMapping, already tried with annotation uses and really I don't know if this is posible by qualifiedBy
@Mapper(componentModel = "spring")
public interface PersonMapper {
@Mapping(target="identificationEntity", qualifiedBy=IdentificationMapper.class)
PersonEntity toPersonEntity(Identification identification);
}
Please some help with this. :D
From what I understood you would like to use the IdentificationMapper
to map the Identification
into IdentificationEntity
.
You almost got it.
You need to tell MapStruct to map identification
into the identificationEntity
from the PersonEntity
.
E.g.
@Mapper(componentModel = "spring", uses = {IdentificationMapper.class})
public interface PersonMapper {
@Mapping(target = "identificationEntity", source = "identification")
PersonEntity toPersonEntity(Identification identification);
}
The IdentificationMapper
stays the same.
Regarding the qualifiedBy
. That is needed when you want to map some properties in a special way. For example to upper case some strings, but only on those specific properties. There you need to use the MapStruct @Qualifier
to qualify your methods. You can read more about them in the Mapping method selection based on qualifiers from the documentation