使用mapstruct映射嵌套对象

时间:2016-06-13 17:03:26

标签: java spring mapstruct

我创建如下的映射。如何将平面对象属性(如街道,城市等)映射到域对象中的嵌套地址。当我尝试时遇到错误:

  

[ERROR]诊断:返回未知属性“address.postalCode”   类型。               @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);

和班级......

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
}

2 个答案:

答案 0 :(得分:6)

当您尝试使用它时,仍然支持嵌套在目标端。有一个功能请求(issue #389),但我们还没有实现这一点。

答案 1 :(得分:0)

我找不到在一种方法中做到这一点的方法。这是我的解决方案:

@Mapper
public interface DtoObjectMapper {

    Address toAddress(DtoObject dtoObject);

    DomainObject toDomainObject(DtoObject dtoObject, Address address);

}

使用时;

@Component
public class SomeClass {

    @Autowired
    private DtoObjectMapper dtoObjectMapper;

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