我需要将具有嵌套对象(深)的对象的属性映射到 DTO 对象。实际上,我想将复杂对象压缩为具有甚至嵌套对象的所有属性的简单 DTO。我试过 BeanUtils 但这也不能做深拷贝。所以我正在探索 Dozer 来实施该解决方案。但即使是 Dozer 也在映射第一级属性,而不是深层嵌套对象属性。
这是我的课程:
public class Child1 {
private String name = "MyName";
private String address = "ABC";
public TestDTO dto = new TestDTO("50", "USA");
public TestDTO getDto() {
return dto;
}
public void setDto(TestDTO dto) {
this.dto = dto;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class TestDTO {
public TestDTO(){}
public TestDTO(String age, String country) {
super();
this.age = age;
this.country = country;
}
private String age = "27";
private String country = "Canada";
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
这是我想要缩小所有 te 属性的目的地(即使是嵌套对象 TestDTO :
public class TestFacade {
public String name ;
public String address;
private String age ;
private String country ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
我的映射文件(我也尝试过没有配置文件,但它不起作用,所以我添加了一个映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mapping>
<class-a>Child1</class-a>
<class-b>TestFacade</class-b>
</mapping>
<mapping>
<class-a>TestDTO</class-a>
<class-b>TestFacade</class-b>
<field>
<a is-accessible="true">country</a>
<b is-accessible="true">country</b>
</field>
<field>
<a>age</a>
<b is-accessible="true">age</b>
</field>
</mapping>
最后是我的测试文件:
public class QuickTest {
public static void main(String[] args) {
Child1 ch = new Child1();
System.out.println("Get" + ch.getDto().getCountry());
List myMappingFiles = new ArrayList();
myMappingFiles.add("dozerMapping.xml");
DozerBeanMapper mapper = new DozerBeanMapper(myMappingFiles);
TestFacade f = mapper.map(ch, TestFacade.class);
System.out.println(ToStringBuilder.reflectionToString(f));
}
}
这是输出:
TestFacade@13adc56[name=MyName,address=ABC,age=<null>,country=<null>]
嵌套对象的年龄和国家属性没有映射?