2017-10-09 61 views
1

我有使用情況下,我需要映射或特定領域的地圖只有特定領域的DTO - >模型中使用地圖,結構

例如填充數據:我有我需要轉換爲UserDTO用戶模型只有 特殊字段,如用戶名和accountId。

MODEL:

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; 

    } 

是有在地圖結構,這樣我可以向目的地

從源僅特定字段映射例如任何方式: UserMapper mapper = Mappers.getMapper(UserMapper.class);

mapper.map(fieldsToFetch,source,destination);

+0

到目前爲止您嘗試了什麼? –

+0

@DarrenForsythe我在map-struct文檔中看到,我沒有發現任何支持上述要求,這就是爲什麼我來到SO。對於每個機構來說,通常的做法是說出你迄今爲止甚至沒有理解問題而嘗試了什麼。不意味着在這裏傷害 –

回答

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可能會爲所有領域,不只是嵌套字段作爲例子的工作。

+0

我們是需要排除的硬編碼領域。我的問題是不同的。有沒有什麼動態的方法可以做到這一點?例如我正在開發一個API,它將請求參數作爲fieldsToFetch = username,salary(即API響應應該只包含用戶名和工資)。 fieldsToFetch是客戶標準。 –

+0

你在找什麼不能工作。 Map結構爲映射類_at構建time_生成java代碼。你只會在運行時知道這些字段,你將不得不看看在運行時使用反射來解決這個問題的工具。請注意,構建時使用maptruct的原因不是在運行時產生反射代價。 – Alpar