top of page

Batch Apex in Salesforce

Batch class in salesforce :

When we want to deal with large number of records we go for batch apex. The code inside batch class runs asynchronously i.e. in future context. The governor limit are also more as compared to synchronous code.


When we use batch apex we implements Database.batchable() interface

The Database.batchable() contains three methods that we need to defined inside batch class and they are, 1) start 2) execute 3) Finish

Syntax:


global class batch implements Database.Batchable <sObject> {

global (Database.QueryLocator or Iterable<sobject>)

start(Database.BatchableContext bc) {

//query on object;

//return Database.getQueryLocator(query);

}

global void execute(Database.batchableContext bc, List <SObject> scope) {

//some processing.

}

global void finish(Database.BatchableContext bc) {

//job such as sending email or calling another batch class

}

}


1.) Start method:



The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.


Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}


This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.


2.) Execute Method:


The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.


Syntax: global void execute(Database.BatchableContext BC, list<P>){}


This method takes the following:

o A reference to the Database.BatchableContext object.

o A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.

Batches of records execute in the order they are received from the start method.


3.) Finish Method:


Syntax: global void finish(Database.BatchableContext BC){}


The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.

The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

Recent Posts

See All

Comments


Subscribe to Path2sfdc newsletter

Thanks for submitting!

  • Twitter
  • trailhead
  • Linkedin

© 2024 by Path2sfdc

bottom of page