简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM