mapstruct / mapstruct.org

Web site of the MapStruct project
63 stars 40 forks source link

Mapping fields to nested object using custom method #101

Closed coffman21 closed 4 years ago

coffman21 commented 4 years ago

Better see SO question and answer than explaining the issue.
https://stackoverflow.com/questions/58952700/mapping-fields-to-nested-object-using-custom-method
I couldn't find an explanation for case like that one - when there is object which has fields on it, which should be mapped to an object inside DTO, using manually implemented method. The closest explanation is 5.4. Invoking other mappers part, however this didn't lead me to solution. I wouldn't mind to contribute with this part of documentation, otherwise please argue, because I don't find this solution an obvious.

sjaakd commented 4 years ago

@coffman21 you mean the default method in the first answer?

@Mapper
public interface DtoMapper {

    @Mapping( target = "amount", source = "request" /* the param name */ )
    MyDto convert(IncomingRequest request);

    // @Mapping( /* what should I use here ? Answer: nothing its an implemented method.. @Mapping does not make sense */ )
    default Amount createAmount(IncomingRequest request) {
        long value = ....
        int exponent = ....
        int currency = ....
        return new Amount(value, exponent, currency);
}

I guess you'll have to piece 2 parts of our documentation together (if you mean my first answer)

  1. Example 12 explains how to map a source parameter.
  2. Chapter 5.3 talks about the nested mappings and automatically generating code for this. What it doesn't mention is that this feature was added on later. Initially you had to define all nested mappings yourself, and you can still do that to aid MapStruct.

Perhaps 2. deserves more explanation and a more elaborate example in our examples repository.

Is this what you mean?

WDYT?

coffman21 commented 4 years ago

@sjaakd Exactly that. There is a tip suggested:

Instead of configuring everything via the parent method we encourage users to explicitly write their own nested methods. This puts the configuration of the nested mapping into one place (method) where it can be reused from several methods in the upper level, instead of re-configuring the same things on all of those upper methods.

I would add there an example of usage, because I find it not quite intuitive.
Thanks for helping.

sjaakd commented 4 years ago

@coffman21 thanks for the suggestion.. could you issue a pr? The doc can be found in our main repository

coffman21 commented 4 years ago

@sjaakd I provided a PR to main repository, please take a look if something should be changed.

sjaakd commented 4 years ago

done