Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct: map nested object properties to properties

Tags:

java

mapstruct

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?

like image 995
JIN Avatar asked May 24 '18 13:05

JIN


2 Answers

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.

like image 180
Mustafa Avatar answered Sep 17 '22 15:09

Mustafa


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);

}
like image 41
Filip Avatar answered Sep 19 '22 15:09

Filip