here is an example, why storing in Set
sobjects is a not a best idea.
Id someAcctId = '001Z000001ORdLz';
Account acct1 = [
select Id, Name
from Account
where Id = :someAcctId
];
Account acct2 = [
select Id, Name
from Account
where Id = :someAcctId
];
acct2.Name += 'Z';
Set<Account> accts = new Set<Account>();
accts.add(acct1);
accts.add(acct2);
System.debug('accts.size():' + accts.size()); // accts.size():2 oops, size is 2
System.debug('accts:' + accts); // two account records are printed
So uniquness of records is defined NOT ONLY by Id, but rest of the fields are considered as well.
in order to correct storing records to update, you can use Map<Id, Sobject>
Id someAcctId = '001Z000001ORdLz';
Account acct1 = [
select Id, Name
from Account
where Id = :someAcctId
];
Account acct2 = [
select Id, Name
from Account
where Id = :someAcctId
];
acct2.Name += 'Z';
Map<Id, Sobject> sobjectsToUpdate = new Map<Id, Sobject>();
sobjectsToUpdate.put(acct1.Id, acct1);
sobjectsToUpdate.put(acct2.Id, acct2);
System.debug('sobjectsToUpdate.size():' + sobjectsToUpdate.size()); // sobjectsToUpdate.size():1 nice!
System.debug('sobjectsToUpdate:' + sobjectsToUpdate); // one account record is printed
Try to put in sets (or in keys of map) immutable types
in your current case, if you want to call upsert
DML, you can have two collections: Map
to store records to update with key by Id
and List
for records to insert. Merge them into one collection and do upsert
.
Map<Id, Sobject> sobjectsToUpdate = new Map<Id, Sobject>();
List<Sobject> sobjectsToInsert = new List<Sobject>();
...
List<Sobject> sobjectsToUpsert = new List<Sobject>();
sobjectsToUpsert.addAll(sobjectsToUpdate);
sobjectsToUpsert.addAll(sobjectsToInsert);
upsert sobjectsToUpsert;