Reputation: 146
I have Entity class with fields:
I have DTO class with fields:
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
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