+ Start a Discussion
Vigneshwaran LoganathanVigneshwaran Loganathan 

Calling Batch Apex from Class for DML

Hello, 

I have to bulk insert in two objects which are parent and child. I have mapped parent's external id to child records.

I'm calling batch apex from normal class which inserts both. But Child records cant able to find parent External ID as it runs in parallel instead of one after one. 

Error : System.DmlException: Upsert failed. First exception on row 0; first error: INVALID_FIELD, Foreign key external ID
public static void saveFile()
     {         
              Try
                {                                                
                        if(FinalTarList.size()>0)  // Parent
                         {
                         SPL_BatchImportGild splTar = new SPL_BatchImportGild(FinalTarList); // should execute first
                         Database.executeBatch(splTar,200);
                         success = true;
                         }
                        
                        if(FinalcycdetCopy.size() > 0)
                            {
                             SPL_BatchImportGild splTarDet = new SPL_BatchImportGild(FinalcycdetCopy); // should execute after parent Insertion. 
                             Database.executeBatch(splTarDet,200); 
                            }                            
                 }
                       
          }

Is there a way to achieve this.? please suggest me if there are alternatives. 

Thanks 
Vignesh
Best Answer chosen by Vigneshwaran Loganathan
Vigneshwaran LoganathanVigneshwaran Loganathan
I've found a way. Added both object records in sObject list and passed to Batch Apex. there i had split parent and child and inserted Parent first and Child next. Thanks :) 

All Answers

Vigneshwaran LoganathanVigneshwaran Loganathan
I've found a way. Added both object records in sObject list and passed to Batch Apex. there i had split parent and child and inserted Parent first and Child next. Thanks :) 
This was selected as the best answer
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!
poenar ioana 6poenar ioana 6
Thanks!