1

我有带有字段的实体类:

  1. 客户端发件人;
  2. 客户收件人;

我有带有字段的 DTO 类:

  1. 长发件人ID;
  2. 长收件人ID;

如果我这样做:

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

你能建议我如何映射它们吗?

4

1 回答 1

5

在解决错误之前,您需要定义方法并使用qualifedByor 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);
}
于 2017-03-23T21:18:40.803 回答