仅映射DTO中的特定字段 - >模型使用Map-Struct

时间:2017-10-09 11:59:37

标签: java spring datamapper mapstruct

我有用例,我需要为特定字段映射或填充数据

例如:我有一个用户模型,我只需要转换为UserDTO 特定字段,如username和accountId。

模特:

public class UserCore{

        private String accountId;

        private String username;
        private String workEmail;
        private String firstName;
        private String password;
        private String hashedPassword;

    }

UserDTO:

public class UserCoreDTO{

        private String accountId;

        private String username;
        private String workEmail;
        private String firstName;
        private String password;
        private String hashedPassword;

    }

map-struct 中是否存在任何方式,以便我只能将特定字段从源映射到目标

例如:

UserMapper mapper = Mappers.getMapper( UserMapper.class );
mapper.map(fieldsToFetch,source,destination);

1 个答案:

答案 0 :(得分:0)

以下是docs的一个示例:

@Mapper
public interface FishTankMapper {

    @Mappings({
        @Mapping(target = "fish.kind", source = "fish.type"),
        @Mapping(target = "fish.name", ignore = true),
        @Mapping(target = "ornament", source = "interior.ornament"),
        @Mapping(target = "material.materialType", source = "material"),
        @Mapping(target = "quality.report.organisation.name", source = "quality.report.organisationName")
    })
    FishTankDto map( FishTank source );
}

ignore = true可能适用于所有字段,而不仅仅是示例中的嵌套字段。