【问题标题】:Dto from multiple string in Entity mapstructDto来自实体mapstruct中的多个字符串
【发布时间】:2020-05-14 08:45:54
【问题描述】:

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

我想知道是否有办法从多个实体的字段映射到单个 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

是否可行
@Mapper(componentModel = "spring")
public interface PersonMapper {


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

请对此提供一些帮助。 :D

【问题讨论】:

    标签: java spring mapping dto mapstruct


    【解决方案1】:

    据我了解,您希望使用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 中阅读有关它们的更多信息

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2018-11-06
      相关资源
      最近更新 更多