簡體   English   中英

從具有相同類型的多個字段的字符串構造到嵌套對象

[英]Mapstruct from string to nested object for multiple fields with the same type

我有Entity類的字段:

  1. 客戶發件人;
  2. 客戶收件人;

我有DTO課的字段:

  1. long senderId;
  2. long recipientId;

如果我喜歡這樣:

@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()))")
})

你能告訴我如何映射它們嗎?

在解決錯誤之前,您需要定義方法並使用qualifedByqualifiedByName 有關此處的更多信息,請參閱文檔。

您的映射器應如下所示:

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM