来自实体mapstruct中多个字符串的Dto

Dto from multiple string in Entity mapstruct

我一直在 SO 中寻找这个问题,但找不到答案。

我想知道是否有办法从多个实体的字段映射到单个 DTO,但使用另一个映射器映射到封装的 DTO。

一个例子:

这是我的实体:

public class Identification{
    long dbId;
    String id;
    String type;
    String completeName;
    boolean status;
}

我的 DTO:

public class PersonEntity{
    String completeName;
    IdentificationEntity identificationEntity;
}

public class IdentificationEntity{
    String documentNumber;
    boolean status;
    String documentType;
}

我创建了我的映射器:

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


}

但我不知道如何使用映射器从 PersonEntity 映射 IdentificationEntity。我的意思是如果有不使用@AfterMapping 的方法,已经尝试使用注释 uses 并且我真的不知道 qualifiedBy[=34 是否可行=]

@Mapper(componentModel = "spring")
public interface PersonMapper {


    @Mapping(target="identificationEntity", qualifiedBy=IdentificationMapper.class)
    PersonEntity toPersonEntity(Identification identification);
}

请帮忙解决这个问题。 :D

据我了解,您希望使用 IdentificationMapperIdentification 映射到 IdentificationEntity

你快明白了。

您需要告诉 MapStruct 将 identificationPersonEntity 映射到 identificationEntity

例如

@Mapper(componentModel = "spring", uses = {IdentificationMapper.class})
public interface PersonMapper {


    @Mapping(target = "identificationEntity", source = "identification")
    PersonEntity toPersonEntity(Identification identification);
}

IdentificationMapper保持不变。

关于qualifiedBy。当您想以特殊方式映射某些属性时,这是必需的。例如,大写一些字符串,但仅限于那些特定的属性。您需要使用 MapStruct @Qualifier 来限定您的方法。您可以在 Mapping method selection based on qualifiers 文档

中阅读更多关于它们的信息