Florent06
Florent06

Reputation: 988

Map nested fields with MapStruct

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

Here is my Mapper:

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

Upvotes: 0

Views: 1735

Answers (1)

Filip
Filip

Reputation: 21451

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

Upvotes: 2

Related Questions