Using Database.Batchable Interface with Example

As Salesforce consultants we often face the challenge to update a chunk of records in the platform. Before we do that we think of the possibilities of what is the best approach and to tackle this challenge. Many of us will choose dataloader if we have simple or no logic, and only a few will choose the GODly way.

These couple of days, I am facing that challenge and I must admit I really enjoy writing that code.

Implementing the Database.Batchable Interface

When it comes to writing a BATCH class, we need to implement the Database.Batchable interface. Database.Batchable interface contains three methods that must be implemented.

start method
public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

This method collects the records or object and pass them to the execute interface method. When used this method returns either a Database.QueryLocator object or an iterable that contains the records or objects passed to the job.

When you want to use a query (SELECT) to generate the scope of objects in the batch job, you can use Database.QueryLocator object. By using this, we bypass the governor limits for the total number of records retrieved by SOQL queries.

Example
A batch Apex job for Account object can return a QueryLocator for all account records (up to 50 million records) in an org.
execute method
public void execute(Database.BatchableContext BC, list<P>){}

To do the required processing for each chunk of data, use the execute method. We call this method for each batch of records that we want to pass.

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 you’re using a Database.QueryLocator, use the returned list.

Batches of records tend to execute in the order in which they’re received from the start method. However, the order in which batches of records execute depends on various factors, and the order of execution isn’t guaranteed.

finish method
public void finish(Database.BatchableContext BC){}

We use this method when we want to send confirmation emails or execute post-processing operations. This method is called after all batches are processed.

Example

 

//Batch class
//define your Database.Batchable interface at the beggining of your class
global with sharing class Class_BATCH implements Database.Batchable<sObject>{
  
  //start method
  global Database.QueryLocator start(Database.BatchableContext BC){
     //add your query in the Database.getQueryLocator
     return Database.getQueryLocator('SELECT Id FROM Account');
  }
  //execute method
  global void execute(Database.BatchableContext BC, List<Account> accList){
     System.debug('***Batch Started***');
     //call your batch method here, or just write your logic instead.
     performBatchActions(accList);
  }

  //finish method
  global void finish(Database.BatchableContext BC){
     System.debug('***Batch Finished***');
  }
  //method to execute
  private void performBatchActions(Account[] accList){
  //write your logic here
  }
}
//Test class
@isTest
private class Class_BATCH _TEST extends TP_TestFactory
{ 
   private static String ADMIN_USER_NAME = 'my_special_name@user.example.com';
   @TestSetup
   private static void dataSetup() {
   // define your test requirements here
   }

   @IsTest 
   static void test_Class_BATCH()
   {
    //start & end your test logic
    Test.startTest();
    //call your batch
    Class_BATCH batch = new Class_BATCH();
    Database.executeBatch(batch ,200);
    Test.stopTest();
    
    //write your assertion here
    }
}

How to execute your Batch

  1. Go to Setup –> Open Developer Console.
  2. Select “Debug” tab –> Open Execute Anonymous Window
  3. In this window, type
Database.executeBatch(new MyClass());

Please make sure to replace MyClass with the apex batch class name that you have written/want to execute.

 

Want to learn more?

Learn about Mocking External Objects and Code Coverage With Examples
Read more about Batch Apex
Check out this trailhead about the Use of Batch Apex

Share this article...

Salesforce Mentor, with 10 years Salesforce experience, Hardcore Admin & Guru Developer, Geek, Animal lover, and dog & cat rescuer activist. Lifetime student, Stand-Up comedian wannabe, Photographer, Gamer, Anime lover, and coffee addict. Spreading Salesforce love and teaching beyond my capacity. Aiming to become Tech Architect!

Leave a Reply

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