Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do deep copy of inner objects from Hibernate Entity to DTO?

I have entity class

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
}

when I use BeanUtils.copyProperties(); (from spring/apache common) it copies the id and name alone. How to copy the address and profile also?

If custom util has to be written, could you please share the snippet?

like image 930
Shakthi Avatar asked Oct 16 '22 18:10

Shakthi


1 Answers

BeanUtils, cloning OR serialization would not work here as the inner data types are different. I would suggest you to set the fields of StudentDTO manually. You could use conversion constructor for AddressDTO and ProfileDTO. Copy constructor is the legal name, but since we are converting type also, better name would be a conversion constructor instead.

An example of conversion constructor in JDK is ArrayList(Collection<? extends E> c) , i.e. https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection- which generates an ArrayList from any Collection object and copy all items from Collection object to newly created ArrayList object.

Example:

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());

where AddressDTO (OR ProfileDTO for that matter) including a conversion constructor looks like:

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;
    }
}

prints

StudentDTO [id=1, name=myStudent, address=AddressDTO [city=myCity]]

like image 103
gargkshitiz Avatar answered Oct 21 '22 01:10

gargkshitiz