1

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?

1
  • 1
    This is a bug. I have created #1148 for this Commented Mar 22, 2017 at 18:14

1 Answer 1

6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.