![](/img/trans.png)
[英]Map multiple source fields to same type target fields with Mapstruct
[英]Mapstruct from string to nested object for multiple fields with the same type
我有Entity類的字段:
我有DTO課的字段:
如果我喜歡這樣:
@Mappings({ @Mapping(source = "senderId", target = "sender.id"), @Mapping(source = "recipientId", target = "recipient.id") })
Mapstruct將生成如下代碼:
public Entity toEntity(DTO) {
//...
entity.setSender( dtoToClient( dto ) );
entity.setRecipient( dtoToClient( dto ) );
//...
protected Client dtoToClient(Dto dto) {
Client client = new Client();
client.setId( dto.getRecipientId() ); // mapstruct takes recipient id for sender and recipient
return client;
}
}
Mapstruct獲取發件人和收件人的收件人ID而不是收件人ID,以創建客戶端收件人和發件人ID以創建客戶端發件人。
所以我發現更好的方法是使用不那么優雅的表達式,據我所知:
@Mappings({
@Mapping(target = "sender", expression = "java(createClientById(dto.getSenderId()))"),
@Mapping(target = "recipient", expression = "java(createClientById(dto.getRecipientId()))")
})
你能告訴我如何映射它們嗎?
在解決錯誤之前,您需要定義方法並使用qualifedBy
或qualifiedByName
。 有關此處的更多信息,請參閱文檔。
您的映射器應如下所示:
@Mapper
public interface MyMapper {
@Mappings({
@Mapping(source = "dto", target = "sender", qualifiedByName = "sender"),
@Mapping(source = "dto", target = "recipient", qualifiedByName = "recipient")
})
Entity toEntity(Dto dto);
@Named("sender")
@Mapping(source = "senderId", target = "id")
Client toClient(Dto dto);
@Named("recipient")
@Mapping(source = "recipientId", target = "id")
Client toClientRecipient(Dto dto);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.