13

Assume I have the following objects:

class Person {
    String firstName;
    String lastName;
}

class PersonBLO {
    Person person;
    Integer foo; // Some calculated business property
}

class PersonDTO {
    String firstName;
    String lastName;
    Integer foo;
}

I find myself writing the following mapper:

@Mapping(target = "firstName", source = "person.firstName")
@Mapping(target = "lastName", source = "person.lastName")
PersonDTO personBLOToPersonDTO(PersonBLO personBLO);

Is it possible to automagically map all person.* attributes to the corresponding * attributes?

2 Answers 2

16

Now, with version 1.4 and above of mapstruct you can do this:

@Mapping(target = ".", source = "person")
PersonDTO personBLOToPersonDTO(PersonBLO personBLO);

It will try to map all the fields of person to the current target.

Sign up to request clarification or add additional context in comments.

Comments

2

Using wildcards is currently not possible.

What you can do though is to provide a custom method that would just invoke the correct one. For example:

@Mapper
public interface MyMapper {

default PersonDTO personBLOToPersonDTO(PersonBLO personBLO) {
    if (personBLO == null) {
        return null;
    }
    PersonDTO dto = personToPersonDTO(personBlo.getPerson());
    // the rest of the mapping

    return dto;
}

PersonDTO personToPersonDTO(PersonBLO source);

}

1 Comment

Thanks! So either way I have to implement part of the mapping by hand. Should I create a feature request ticket on GitHub or is this something that does not fit in the roadmap?

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.