Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Created December 13, 2019 07:23
Show Gist options
  • Save mhamzas/eee6a82d5543ed6e853858d4156b1300 to your computer and use it in GitHub Desktop.
Save mhamzas/eee6a82d5543ed6e853858d4156b1300 to your computer and use it in GitHub Desktop.
Upserts with Generic sObjects - Salesforce
list < sObject > sObjList = new list < sObject > (); //This routine would get the rows to update/insert from some business logic
sObjList = myClass.getObjectRowsToUpdate();
set < string > newExtIDSet = new set < string > ();
string myExternalIDField = 'myExternalID__c'; //Loop through and build a set of External IDs that should be used for a query
for (sObject sObjItem: sObjList) {
tempStr = string.ValueOf(sObjItem.get(myExternalIDField));
if (string.isBlank(tempStr) == false) {
newExtIDSet.add(tempStr);
}
}
list < sObject > sObjExistingList = new list < sObject > (); //Now use those external IDs for matching
string sQuery = 'Select ID, ' + myExternalIDField + ' From myUpdateObj__c' + ' Where ' + myExternalIDField + ' IN :newExtIDSet';
sObjExistingList = database.query(sQuery); //Now loop through the matches and build a map of that external ID to the actual Salesforce ID
map < string, string > extIDToIDMap = new map < string, string > ();
for (sObject sObjItem: sObjExistingList) {
extIDToIDMap.put(string.valueOf(sObjItem.get(myExternalIDField)), sObjItem.ID);
} //Now loop through the items to be updated/inserted and assign the Salesforce IDs to that items that matches by the External ID
list < sObject > sObjInsertList = new list < sObject > ();
list < sObject > sObjUpdateList = new list < sObject > ();
for (sObject sObjItem: sObjList) {
if (extIDToIDMap.containsKey(string.ValueOf(sObjItem.get(myExternalIDField)))) {
sObjItem.ID = extIDToIDMap.get(string.ValueOf(sObjItem.get(myExternalIDField)));
sObjUpdateList.add(sObjItem);
} else {
sObjInsertList.add(sObjItem);
}
}
if (sObjUpdateList.size() > 0) {
update sObjUpdateList;
}
if (sObjInsertList.size() > 0) {
insert sObjInsertList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment