• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

Batch Apex

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.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 querylocator 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 aQueryLocator for all account records (up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object that returns aQueryLocator for all account records in an organization.

Learn more about Salesforce Interview Questions in this blog post.
  • 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.

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 Mehod:

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.

  • 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 indepth understanding of Salesforce click on

Summary
Review Date
Reviewed Item
Batch Apex
Author Rating
5

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Batch Apex"

Leave a Message

Your email address will not be published. Required fields are marked *

Site Disclaimer, Copyright © 2016 - All Rights Reserved.