如何从Hibernate Entity到DTO深层复制内部对象?

时间:2018-05-10 09:52:26

标签: java spring-bean apache-commons-beanutils

我有实体类

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)时,它会单独复制idname。如何复制addressprofile

如果必须编写custom util,请分享一下代码段吗?

2 个答案:

答案 0 :(得分:2)

由于内部数据类型不同,

BeanUtils 克隆序列化在此处不起作用。我建议你手动设置StudentDTO的字段。您可以将 转换构造函数 用于AddressDTO和ProfileDTO。复制构造函数是合法的名称,但由于我们也在转换类型,因此更好的名称将是转换构造函数。

JDK中的转换构造函数的示例是ArrayList(Collection<? extends E> 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]]

答案 1 :(得分:1)

您可以尝试使用SerializationUtils.clone()。此方法深度克隆您的对象。但是你应该将你的对象标记为Serializable。

https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SerializationUtils.html#clone(T)