我有实体课
public Class StudentEntity{
private int id;
private String name;
private AddressEntity address;
private ProfileEntity profile;
//getter setter
}
public Class StudentDTO{
private int id;
private String name;
private AddressDTO address;
private ProfileDTO profile;
//getter setter
}
当我使用BeanUtils.copyProperties(); (来自spring / apache common)它只复制id和name.如何复制地址和个人资料呢?
最佳答案
BeanUtils,克隆或序列化在这里不起作用,因为内部数据类型不同.我建议你手动设置StudentDTO的字段.您可以使用AddressDTO和ProfileDTO的转换构造函数.复制构造函数是合法的名称,但由于我们也在转换类型,因此更好的名称将是转换构造函数.
JDK中的转换构造函数的示例是ArrayList(Collection@H_403_19@ c),即https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-,其从任何Collection对象生成ArrayList并将所有项目从Collection对象复制到新创建的ArrayList对象.
例:
StudentEntity studentEntityObj = new StudentEntity();
studentEntityObj.setId(1);
studentEntityObj.setName("myStudent");
AddressEntity addressEntityObj = new AddressEntity();
addressEntityObj.setCity("myCity");
studentEntityObj.setAddress(addressEntityObj);
// All above lines would be taken care of already (i.e. data is filled from DB)
StudentDTO studentDTOObj = new StudentDTO();
// Call conversion constructor
AddressDTO addressDtoObj = new AddressDTO(addressEntityObj);
studentDTOObj.setAddress(addressDtoObj);
studentDTOObj.setId(studentEntityObj.getId());
studentDTOObj.setName(studentEntityObj.getName());
System.out.println(studentDTOObj.toString());
其中包括转换构造函数的AddressDTO(OR ProfileDTO)如下所示:
public class AddressDTO {
private String city;
// Conversion constructor
public AddressDTO(AddressEntity a) {
this.city = a.getCity();
}
@Override
public String toString() {
return "AddressDTO [city=" + getCity() + "]";
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
版画
StudentDTO [id = 1,name = myStudent,address = AddressDTO [city = myCity]]