Sabfir
Sabfir

Reputation: 146

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?

Upvotes: 1

Views: 10548

Answers (1)

Filip
Filip

Reputation: 21393

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

Upvotes: 6

Related Questions