从具有相同类型的多个字段的字符串构造到嵌套对象

时间:2017-03-22 12:01:21

标签: java mapstruct

我有包含字段的实体类:

  1. 客户发件人;
  2. 客户收件人;
  3. 我的DTO课程包含字段:

    1. long senderId;
    2. long recipientId;
    3. 如果我喜欢这样:

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

      你能告诉我如何映射它们吗?

1 个答案:

答案 0 :(得分:2)

在解决错误之前,您需要定义方法并使用qualifedByqualifiedByName。有关此文档中here的更多信息。

您的映射器应如下所示:

@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);
}