0

In Spring there's this nice automatic convertion between entities and DTOs:

@Mapping(source = "senderId", target = "senderId")
@Mapping(source = "text", target = "text")
MessageGetDTO convertEntityToMessageGetDTO(Message message);

Here we have the convertion of the server's internal representation of a Message entity to the corresponding DTO that will be sent to the client.

Now assume we want the DTO to have different (related) data than the entity: Instead of revealing the sender's ID to the client, we want to send the sender's name as a String.

The Message entity doesn't have the sender's name, but a simple method could get that name from the database, using senderId.

So here's my question: How can one of these automated mappings be made to use a method instead of an attribute?

@Mapping(source = "getSenderName()", target = "senderName")
                         ^
Duke
  • 386
  • 2
  • 13

1 Answers1

1

I think you are looking for expressions.
It would be: @Mapping( target = "senderName", expression = "java(getSenderName())" )
More help: https://www.tutorialspoint.com/mapstruct/mapstruct_using_expression.htm

Joja
  • 36
  • 2