Batch Apex

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

Batch Apex in Salesforce

Batch Apex:

To use batch Apex, we must write an Apex class that implements the Salesforce-provided interface Database. Batchable, and then invoke the class programmatically. The Database. The batchable interface contains three methods that must be implemented:

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. This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job. Use the Database.QueryLocator object when we are using a simple query (SELECT) to generate the scope of objects used in the batch job. If we use a query locator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed. For example, a batch Apex job for the Account object can return query locator for all account records (up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object that returns query locator for all account records in an organization.

 

Salesforce Interview Questions

 

Execute Method

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

  • A reference to the Database.BatchableContext object.
  • A list of sObjects, such as List<sObject>, or a list of parameterized types. If we are using a Database.QueryLocator, the returned list should be used.
  • Batches of records are not guaranteed to execute in the order they are received from the start method.

Sample syntax :

Global Void execute(Database.BatchableContext BC, List<P>){}

 

Finish Method:

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

Syntax :

global void finish(Database.BatchableContext ){}

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 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.

Inclined to build a profession as SalesForce Developer? Then here is the blog post on, explore SalesForce Training

Sample Batch Apex  Program:

Global class UpdateOpportunityLeader implements Database.Batchable<SObject>
 {
 Public String Query=“'Select Id,Leader__c,(Select Id,opportunityId,UserId,TeamMemb
 erRole From OpportunityTeamMembers where TeamMemberRole='Lead Qualifier' Ord
 er by CreatedDate Desc Limit 1) from Opportunity'“;
 Global Database.QueryLocator Start(Database.BatchableContext BC)
 {
 System.Debug(Database.getQueryLocator(query));
 return Database.getQueryLocator(query);
 }
 Global void Execute(Database.BatchableContext BC,List<Opportunity> opportunities)
 {
 List<Opportunity> opp =new List<Opportunity>();
 for(Opportunity objOpp:opportunities)
{
 if(objOpp.OpportunityTeamMembers.Size()>0)
 {
 for(OpportunityTeamMember team :objOpp.OpportunityTeamMembers)
 {
 if(team.UserId !=null)
 {
 if(team.TeamMemberRole=='Lead Qualifier')
 objOpp.Leader__c =team.UserId;
 opp.add(objOpp);
 }
 }
 }
 else
 {
 objOpp.Leader__c =null;
 opp.add(objOpp);
 }
 }
 update opp;
 }
 Global void finish(Database.BatchableContext BC)
 {
 AsyncApexJob a = “Select Id, Status, NumberOfErrors, JobItemsProcessed,
 TotalJobItems, CreatedBy.Email
 from AsyncApexJob where Id =:BC.getJobId()”;
 // Send an email to the Apex job's submitter notifying of job completion.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String”“ toAddresses = new String”“ {ABC@gmail.com,xyz@gmail.com'};
 mail.setToAddresses(toAddresses);
 mail.setSubject('Test Batch ' + a.Status);
 mail.setPlainTextBody
 ('The batch Apex job processed ' + a.TotalJobItems +
 ' batches with '+ a.NumberOfErrors + ' failures.');
 Messaging.sendEmail(new Messaging.SingleEmailMessage”“ { mail });
 }
 }

For an in-depth understanding of Salesforce click on

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/15

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.