【问题标题】:Mapstruct from string to nested object for multiple fields with the same typeMapstruct从字符串到嵌套对象,用于具有相同类型的多个字段
【发布时间】:2018-01-19 02:28:22
【问题描述】:

我有带有字段的实体类:

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

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

【问题讨论】:

  • 这是一个错误。我为此创建了#1148

标签: java mapstruct


【解决方案1】:

在解决错误之前,您需要定义方法并使用qualifedBy 或qualifiedByName。更多关于 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2017-09-26
    • 2011-08-05
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多