Sometimes there will be a requirement to copy specified fields from one object to another object.
A classic example will be to update multiple DB fields using Spring. In this case, existing records will be fetched from DB and predefined fields will be copied from the user request. Remaining fields will remain intact. For this scenario below mentioned way will be effective as it does not rely on classic getter and setter way.
Detailed Steps below
Create Original Object
Below is the Order Class along with primitive data type fields and has List of OrderItem
OrderItem is child class of Order Class
Create the Original Object by populating some dummy values.
Create Duplicate Object
Create Duplicate object which is an instance of Order Class populated with minimum field values
Use org.springframework.beans.BeanWrapper to copy specific fields. Logic is mentioned below
Before calling above util method, list down parent and child class fields which needs to be copied.
Iterable<String> itemLevelFields = Arrays.asList("vpn", "desc"); Iterable<String> headerLevelFields = Arrays.asList("buyer", "supplier");
Invoke util method by passing header object with fields to be copied.
copyProperties(order, duplicateOrder, headerLevelFields);
To Copy child object fields pass child object instance (if it list of objects then pass object instance retrieved using index)
Below line copies value from 3rd child object to 1st child object in target Object
copyProperties(order.getItems().get(2), duplicateOrder.getItems().get(0), itemLevelFields);