我有一个用例,我需要为特定字段映射或填充数据
例如:我有一个用户模型,我只需要将其转换为 UserDTO 用户名和帐户 ID 等特定字段。
型号:
public class UserCore{
private String accountId;
private String username;
private String workEmail;
private String firstName;
private String password;
private String hashedPassword;
}
用户数据对象:
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);
最佳答案
这是一个来自 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
可能适用于所有字段,而不仅仅是示例中的嵌套字段。
关于java - 仅映射来自 DTO 的特定字段 -> 使用 Map-Struct 的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645941/