Mapping flat objects to hierarchical objects

In the previous post under MapStruct I showed how to map hierarchial objects to flat objects.

In this post, I will show the reverse i.e., how to map flat objects to hierarchical objects.

We are assuming the property names on source and destination objects are same.

For our example I will use the below model objects

Person

package package9;

public class Person {
    private String name;
    private int age;
    private Address address;

    //Removed toString, getter and setter for brevity
}

Address

package package9;

public class Address {
    private String addressLine1;
    private String addressLine2;

    //Removed getter and setter for brevity
}

PersonDTO

package package9;

public class PersonDTO {
    private String name;
    private int age;
    private String addressLine1;
    private String addressLine2;

    //Removed toString, getter and setter for brevity
}

In this example, we will map PersonDTO object (flat object) to Person (hierarchial object).

More specifically, we have to map “addressLine1” and “addressLine2” of “PersonDTO” class to “Address” class properties.

Remaining properties of “PersonDTO” class will map to properties of “Person” class.

Below is the mapper class that we will use

PersonMapper

1  package package9;
2  
3  import org.mapstruct.Mapper;
4  import org.mapstruct.Mapping;
5  
6  @Mapper
7  public interface PersonMapper {
8      @Mapping(target = "address", source = ".")
9      public Person getModelFromDTO(PersonDTO personDTO);
10 }

In the above mapper class, we are using “@Mapping” annotation with dot operator on the “source” attribute.

The dot operator represents the entire “PersonDTO” object which is the source object in our example.

Since the property names are identical on the source and destination objects. The MapStruct will automatically create an instance of “Address” class and assign “addressLine1” and “addressLine2” of
“PersonDTO” class to “Address” class properties.

In this way we can map flat objects to hierarchial objects.

Below is the complete Main class for your reference

Main class

package package9;

import org.mapstruct.factory.Mappers;

public class Example9 {
    public static void main(String[] args) {
        PersonDTO personDTO = new PersonDTO();
        personDTO.setName("John Doe");
        personDTO.setAge(40);
        personDTO.setAddressLine1("address line 1");
        personDTO.setAddressLine2("address line 2");

        PersonMapper personMapper = Mappers.getMapper(PersonMapper.class);

        Person person = personMapper.getModelFromDTO(personDTO);

        System.out.println(person);
    }
}

Leave a comment