java 使用 mapstruct 映射嵌套对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37795379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping nested object with mapstruct
提问by Piotr Sobolewski
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:
我创建如下映射。如何将平面 dto 对象属性(如(街道、城市等)映射到域对象中的嵌套地址。当我尝试时,出现错误:
[ERROR] diagnostic: Unknown property "address.postalCode" in return type. @Mapping(source = "city", target = "address.city"),
[错误] 诊断:返回类型中的未知属性“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);
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
}
采纳答案by Gunnar
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),但我们还没有开始实现它。
回答by user3088282
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));
}
}