使用 MapStruct 映射嵌套字段

Map nested fields with MapStruct

假设我有这些实体:

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

还有这个 DTO:

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

在我的 DTO 中,我想映射

这是我的映射器:

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

当您映射嵌套字段时,您需要告诉 MapStruct 您希望使用 @Mapping 进行映射的位置和方式。

在你的情况下它看起来像:

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