7

I have a case where i need to do an upsert of different sObjects, and I want to do them all at the same time. I know I can do a multiple records of a SINGLE sObject at the same time if I put them into an array and do an upsert(array) . I was thinking In my case, cast the objects ( a master custom object, a detail custom object,and activities, all instantiated in apex) as sObjects and put them into an sObject array and then do an insert on that... but as of now,that's all i've got...

ideas?

4
  • Wouldn't these Details need the id of the new Master? And Activities need their WhoId set. . .
    – Mike Chale
    Aug 15, 2013 at 20:07
  • you're right about the detail objects.... i guess, i should change the strategy to roll back the changes (update old records and delete new ones) if there is a failure. Aug 15, 2013 at 20:12
  • That's what Database.setSavePoint and Database.rollback are for. Perhaps you should restate your question based on your prior comment. Regardless, I offer a solution for you, in case it helps.
    – sfdcfox
    Aug 15, 2013 at 21:56
  • i'll add this to the number of times you've helped me. thanks fox! Aug 15, 2013 at 22:14

2 Answers 2

7

To roll back a partially failed transaction, you can use the following code:

System.savePoint sp = Database.setSavePoint();
try {
  // your logic here
} catch(exception e) {
  apexpages.addmessages(e);
  database.rollback(sp);
  return null; // assuming you're returning a value. Just return; otherwise.
}
// return a successful result, page reference, etc.
15

You can actually upsert a List of sObject relatively easily. For instance, say you have 3 different custom objects, Foo__c, Widget__c, and Stub__c. You can add them to a list of sObject and upsert them together.

public static void dataSetup(){
   List<sObject> allObjects = new List<sObject>();
   allObjects.add(new Foo__c());
   allObjects.add(new Foo__c());
   allObjects.add(new Foo__c());
   allObjects.add(new Widget__c());
   allObjects.add(new Widget__c());
   allObjects.add(new Widget__c());
   allObjects.add(new Stub__c());
   allObjects.add(new Stub__c());
   allObjects.add(new Stub__c());
   upsert allObjects;
}

The only issue you will have is if you have relationships. The relationships require an Id on the original object to be able to link them together, so they must exist first.

I have an article I wrote detailing this out further.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .