Skip to main content
1 of 3
S.B.
  • 2.1k
  • 3
  • 29
  • 66

Passing a List of Custom Objects to Batch Apex

I am attempting to use batch to handle a deserialized JSON response of 12,000 records to upsert objects.

I currently have a class that makes the webservice callout, deserializes the response, and sets the value of my new custom object list to the response values. I am trying to use batch due to the 10000 DML limit.

How do I pass my list of custom objects from currentCalloutClass into the batch class to handle the upsert? Is there a better a way to do this?

Note: The pasted code will results in:

Illegal conversion from List<Custom_Object__c> to Database.QueryLocator error

Which makes sense, but since I already have the list of objects I need to update I do not need to run a query. Should I be converting my currentCalloutClass into a batchable class? Do I have to set a query?

currentCalloutClass:

public class currentCalloutClass {

     public void currentCalloutClass(){
          jsonStr = '';
          List <Custom_Object__c> cObjList = new list <Custom_Object__c()>;

          ...webservice response stored in jsonStr...

          JSON2ApexConverter calloutGet = (JSON2ApexConverter )JSON.deserialize(jsonStr, JSON2ApexInfo.class);

          for(i = 0; i < calloutGet.object.size(); i++) {
              Custom_Object__c cObj = new Custom_Object__c;
              cObj.custom_field__c = calloutGet.object.field_1;
              cObjList.add(cObj);
              }     

         }
    Database.executeBatch(new batchTestNew(cObjList), 250);

}

batchTestNew

global class batchTestNew implements Database.Batchable<sObject>{

public List <Contact> accountsToParseSet = new List<Custom_Object__c>();

   global batchTestNew(List<Custom_Object__c> accountsToParseGet){
   accountsToParseSet = accountsToParseGet;          
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return accountsToParseSet;
   }

   global void execute(Database.BatchableContext BC, 
                       List<sObject> scope){
      for(sObject s : scope){
           upsert accountsToParseGet;
                  }      
      update scope;
   }

   global void finish(Database.BatchableContext BC){

   }

}
S.B.
  • 2.1k
  • 3
  • 29
  • 66