0
votes

Assume I have these Entities:

public class Address {
    private String id;
    private String address;
    private City city;
}

public class City {
    private int id;
    private Department department;
    private String zipCode;
    private String name;
    private Double lat;
    private Double lng;
}

public class Department {
    private int id;
    private Region region;
    private String code;
    private String name;
}

public class Region {
    private int id;
    private String code;
    private String name;
}

And this DTO:

public class AddressDTO {
    private String address;
    private String department;
    private String region;
    private String zipCode;
}

In my DTO, I'd like to map

  • departement from City/Department/name
  • region from City/Department/Region/name

Here is my Mapper:

@Mapper(componentModel = "spring")
public interface AddressMapper {
    AddressDTO addressToAddressDTO(Address item);
}
1

1 Answers

2
votes

When you are mapping nested fields you need to tell MapStruct from where and how you want to do the mapping with @Mapping.

in your case it will look like:

@Mapper(componentModel = "spring")
public interface AddressMapper {
    
    @Mapping(target = "department", source = "city.department.name")
    @Mapping(target = "region", source = "city.department.region.name")
    @Mapping(target = "zipCode", source = "city.zipCode")
    AddressDTO addressToAddressDTO(Address item);
}