简体   繁体   中英

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

I have Entity class with fields:

  1. Client sender;
  2. Client recipient;

I have DTO class with fields:

  1. long senderId;
  2. long recipientId;

If I do like this:

@Mappings({ @Mapping(source = "senderId", target = "sender.id"), @Mapping(source = "recipientId", target = "recipient.id") })

Mapstruct will generate code like this:

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 takes recipient id for sender and recipient instead of recipient id to create Client recipient and sender id to create Client sender.

So the better way I've found is using expression that is not so elegant as far as I can see:

@Mappings({
      @Mapping(target = "sender", expression = "java(createClientById(dto.getSenderId()))"),
      @Mapping(target = "recipient", expression = "java(createClientById(dto.getRecipientId()))")
})

Could you plz suggest me how to map them?

Until the bug is resolved you will need to define the methods and use qualifedBy or qualifiedByName . More info about there here in the documentation.

Your mapper should look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM