简体   繁体   English

使用mapstruct映射嵌套对象

[英]Mapping nested object with mapstruct

i create mapping like below. 我创建如下的映射。 How to map flat dto object properties like (street, city, etc) to nested address in domain object. 如何将平面对象属性(如街道,城市等)映射到域对象中的嵌套地址。 When I try to I've got an error: 当我尝试我有一个错误:

[ERROR] diagnostic: Unknown property "address.postalCode" in return type. [ERROR]诊断:返回类型中的未知属性“address.postalCode”。 @Mapping(source = "city", target = "address.city"), @Mapping(source =“city”,target =“address.city”),

@Mapper(componentModel = "spring", uses = {})
public interface CompanyMapper {
    @Mappings({
            @Mapping(source = "id", target = "id"),
            @Mapping(source = "street", target = "address.street"),
            @Mapping(source = "city", target = "address.city"),
            @Mapping(source = "postalCode", target = "address.postalCode"),
            @Mapping(source = "province", target = "address.province"),
    })
    DomainObject map(DtoObject dto);

And classes... 和班级......

public class Address {
            private String street;
            private Integer streetNumber;
            private String city;
            private String postalCode;
            private String province;
            //getters and setters
    }
public class DomainObject {
        private String id;
        private Address address;
        //getters and setters
}

public class DtoObject {
        private String id;
        private String street;
        private String city;
        private String postalCode;
        private String province;
        //getters and setters
}

Nesting on the target side as you are trying to use it is not supported yet. 当您尝试使用它时,嵌套在目标端尚不支持。 There's a feature request for this ( issue #389 ), but we did not yet get to implementing this. 有一个功能请求( 问题#389 ),但我们还没有实现这一点。

I could not find a way to do that in one method. 我找不到在一种方法中做到这一点的方法。 Here is my solution : 这是我的解决方案:

@Mapper
public interface DtoObjectMapper {

    Address toAddress(DtoObject dtoObject);

    DomainObject toDomainObject(DtoObject dtoObject, Address address);

}

while using ; 使用时;

@Component
public class SomeClass {

    @Autowired
    private DtoObjectMapper dtoObjectMapper;

    public DomainObject convert(DtoObject dtoObject) {
        return dtoObjectMapper.toDomainObject(dtoObject, dtoObjectMapper.toAddress(dtoObject));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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