Copy Specific fields from one Object to other in Spring

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

Util Method

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.

For E.g.,

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

Output

Source Code

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s