I have Entity class with fields:
- Client sender;
- Client recipient;
I have DTO class with fields:
- long senderId;
- 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?