2

I'm having a hard time visualising the difference between shallow clone and deep clone in apex, for example

Account acct = [SELECT Id, Name, Rating, ParentId FROM Account WHERE Id = '0010O00001qEu5cQAC'][0];

//specifying false for isDeepClone parameter
Account acctDeepClone = acct.clone(false,false);
acctDeepClone.Name = 'DeepClone2';

update acct;

Changing the account name of the shallow clone and then updating the original does nothing to the original, the original name remains.

Also, I cannot update acctDeepClone because it doesn't have an Id field.

If I change my code to the following

Account acct = [SELECT Id, Name, Rating, ParentId FROM Account WHERE Id = '0010O00001qEu5cQAC'][0];

//specifying true for isDeepClone parameter
Account acctDeepClone = acct.clone(false,true);
acctDeepClone.Name = 'DeepClone2';

update acct;

I see the exact same behaviour as in the first snippet, the original account is never updated, and I cannot update the cloned version.

Can someone please show a concrete example (no theory) of how these two really look like?

1

It affects the referenced objects.

If you have a lookup / master detail and you touch the info there and update afterwards, you will see the difference.

In the example below, if you play with false or true you will see that the Parent account is modified or not (respectively)

// Preparation of Hierarchy
Account a1 = new Account(Name = 'Acc 1');
insert a1;

Account a11 = new Account(Name = 'Acc 1.1', ParentId = a1.Id);
insert a11;

// fetch child 1
a11 = [SELECT Name, parent.Name FROM Account WHERE Id = :a11.Id];

// clone it to create a12
Account a12 = a11.clone(false,true);

// touch parent on clone
a12.parent.Name = 'Acc 1 FROM 2';

// update parent info from original child
// if you put true, it will keep 'Acc 1' 
// if you put false it will have 'Acc 1 FROM 2'
update a11.parent;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.