用mapstructMap嵌套字段

izkcnapc  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(815)

假设我有这些实体:

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中,我想Map
离市部门/部门/姓名
来自城市/部门/地区/名称的地区
这是我的Map:

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

w80xi6nr1#

Map嵌套字段时,需要告诉mapstructMap的位置和方式 @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);
}

相关问题