Salesforce Batch Apex | Part 1
Salesforce Batch Apex
In the last EPISODE, we discussed asynchronous apex and its how to use @future methods as well.
In this EPISODE, we will discuss about next type of asynchronous apex type Batch Apex as its one of the very important topic in apex development I will try to put all the necessary stuff.
So let's get started...
What is Batch Apex ?
Batch apex allows you to define a single job that can be broken up into manageable chunks, where every chunk can be processed separately in salesforce which will ultimately help you to bypass the governing limits.
In simple words, when you want to process any large task then its very easy to divide that large task into small-small parts and process them separately which will decrease your the execution time to process the task.
For Example :
If you need to make a field update of every record of Account in your organization, then we have Governor Limits that would restrict us from achieving the above task.
Reason :
In a single transaction, we can process only 10,000 records in the organization then we cannot perform this field update.
How Batch Apex Works ?
In the Batch Apex, it will fetch all the records on which you want to perform the field update and divide them into a list of 200 records and on every 200 records operation is performed separately.
This would help us to execute on more than 10,000 records as It won't perform an operation on all the records in a single transaction instead it dividing them into no, of sub-tasks where each subtask may contain the records up to 2000.
Now, how to do it implement it ? Correct ?
Implementation :
To use the BatchApex concept the Apex class should implement
Database.Batchable interface.
Database.Batchable interface consists of 3 methods, that must be implemented.
1. Start() Method
2. execute method
3. finish method
1. Start() Method :
- Start method is automatically called at the beginning of the batch apex job.
- This method will collect the records or objects on which the operation should be performed.
- These records are broken into sub-tasks and given to execute method.
Syntax :
============================================
global(Database.QueryLocator| Iterable<sObject>)
start(Database.BatchableContaxt bc)
{
}
============================================
The return type of the start method can be :
i) Database.QueryLocator
(or)
ii) Iterable <sObject>
i) Database.QueryLocator :
Use Database.QueryLoactor as a return type to the start method when you are fetching the records using a simple select query.
NOTE : The governing limit says
- A total number of records retrieved by SOQL Queries 50,000.
- A total number of records retrieved by Database.getQueryLocator 10,000.
But, in the Batch Apex, the governing limits for SOQL query are bypassed and we can fetch up to 50 million records using Database.QueryLocator.
Example 1 :
============================================
global Database.QueryLocator start(Database.BatchableContext bc)
{
return Database.getQueryLocator('select id, name from Account');
}
============================================
Example 2 :
Write a start method to fetch all CustomerName, AccountType, from customer object whose AccountType is 'solving'
============================================
global Database.QueryLocator Start(Database.BatchableContext bc)
{
String sql = 'select id, customer_name__c, Account_Type__c from customer__c where Account_Type__c = '+'\'solving\'';
}
============================================
ii) Iterable :
Use Iterable as a return type when you want to use Complex logic or scope to fetch the records for the batch job.
For Example :
============================================
global class MyTest implements Iterable<Account>
{
}
global Iterable<Account> start(Database.BatchableContext bc)
{
return new MyText(); //This should return object of the class that jas implemented iterable interface.
}
============================================
2) Execute Method :
The records which are fetched from the Start method are divided into batches of 200 records each. Now every batch of 200 records are separately passed to them separately and the operation what we want to perform on these records are written in this execute method.
Syntax :
============================================
global void execute(Database.BatchableContext BC, List<p>)
{
}
============================================
- A reference to the Database.BatchableContext object.
- A list of sObject such as List<sObject>, or a list of parameterized types.
i.e., Set 200 records which are passed to the execute method.
When the start method has fetched 1000 records on which we want to perform the operations they are divided into 5 batches/Groups of size 200.
- On every batch or the group, the execute method is called.
- Which means the execute method is called 5 times.
- After executing every group/batch the governing limits are reset for the execute method.
- Once all the batches are executed then finish method will be called to send an email notification or for past execution work.
============================================
global void finish(Database.BatchableContext BC)
{
}
============================================
NOTE :
All the 3 methods of the Batchable interface refers to Database.BatchableContext object Where this object is used to track the progress of the batch job.
Let's have a look at some sample example :
Example 1 :
Write a BatchApex program to update Account Name with-in the Account object with a suffix Mr. before the AccountName.
============================================
global class AccountBatch implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext bc) //start method
{
String query = 'select id, Name from Account';
return Database.getQueryLocator(Query);
}
global void execute(Database.Batchable bc, List<Account> scope)
//execute method
{
for(Account a : scope)
{
a.name='Mr.'+a.name;
}
update scope;
}
global void finish(Database.BatchableContext bc)
//finish method
{
}
}
===========================================
Example 2 :
When a batch apex program to phone no. in the Contact object with the phone no. in the Corresponding Account object. Where Contact is a child of Account.
===========================================
global class ContactUpdate implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContaxt bc)
{
String query = 'select id, phone, Account.phone from Contact';
return Database.getQueryLoactor(query);
}
global void execute(Database.BatchableContext bc, List<Contact> scope)
{
for(contact c: scope)
{
c.phone = c.Account.phone;
}
update scope;
}
global void finish(Database.Batchable Context bc)
{
}
}
============================================
In the above two examples, you can see how we can use batch apex syntax and method to process your apex in batch.
If it's difficult to understand the other apex code please refer the previous episode to clear how you can perform DML operations.
In this way, you can use start(), execute() and finish() methods to implement batch apex for start.
In the next episode, we will discuss how to invoke a batch apex job or how to execute apex job programmatically and use executeBatch().
global class ContactUpdate implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContaxt bc)
{
String query = 'select id, phone, Account.phone from Contact';
return Database.getQueryLoactor(query);
}
global void execute(Database.BatchableContext bc, List<Contact> scope)
{
for(contact c: scope)
{
c.phone = c.Account.phone;
}
update scope;
}
global void finish(Database.Batchable Context bc)
{
}
}
============================================
In the above two examples, you can see how we can use batch apex syntax and method to process your apex in batch.
If it's difficult to understand the other apex code please refer the previous episode to clear how you can perform DML operations.
In this way, you can use start(), execute() and finish() methods to implement batch apex for start.
In the next episode, we will discuss how to invoke a batch apex job or how to execute apex job programmatically and use executeBatch().
WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE BATCH APEX PART 1 EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you
Salesforce Batch Apex | Part 1
Reviewed by
on
Rating:
Good explanation. But both of the example execute method will not work as you expect. You forget to use the variable "Scope". Also new list of variable not needed. you can directly make change in scope list.
ReplyDeleteOh! Thanks for your observation. Please find the updated code.
ReplyDeleteThanks 😊