Salesforce

Batch Apex in Salesforce

In Salesforce, Batch Apex is an asynchronous process in which each process is run on a different thread; that’s why it is an asynchronous process. Using this, we can mass update and delete the records at a time. When compared to the synchronous process, the governor limits are more for this asynchronous process (since each process runs on its own thread). As part of this tutorial, we will discuss how to mass insert, mass update, and mass delete the records from a Salesforce object with examples. We go on with scenario based discussions in each case. Let’s dive into our tutorial.

Scenario:

Sravan is running a company and he is using Salesforce Org to track the salaries of his employees. There are only 200 employees. He stored all their data in an “Account” object in the Salesforce database and he created a custom field which is “Credited” in a checkbox type and update it to true whenever the salary is credited to them. After 2 years, his employee count increased to 2 lakh. It is not able to update this field at one transaction. So he asked the Salesforce developer to help him out of that. Then, the developer suggested the Batch Apex to update 2 lakh records at a time (Batch by Batch).

Batch Apex:

As we already discussed, Batch Apex is an asynchronous process in which each process is run on a different thread. It processes the data batch by batch and has 3 steps while doing this operation. By default, the Batch size is 200, but we can extend up to 2000. The minimum size is 1.

Phase I:

This is the “Start”phase where the records are collected from the Salesforce to be processed. We can utilize the SOQL query to return the records in this phase. Basically, the “Batch” class implements the “Database.Batchable”.

We can define the start() method using the QueryLocator (it returns to Query) from the “Database” class. It is very important to pass the BatchableContext parameter from the “Database” class. Within this method, we can specify the SOQL in the Database.getQueryLocator() method and return it.

See the following method structure:

Phase II:

This is the “Execute” phase where the batch of records are collected from the start phase which are returned by the SOQL query. It processes these records and gets the records again from the query until all the records are completed.

We can define the execute() method by returning as void (empty). It is very important to pass the BatchableContext as the first parameter from the “Database” class which is similar to the start() method. The second parameter is the sObject (Salesforce standard/custom object) inside a “List”.

See the following method structure:

Phase III:

This is the “Finish” phase where the post operations like sending email, displaying messages, etc., are taken in this phase.

We can define the finish() method by returning as void (empty). It is very important to pass the BatchableContext as the first parameter from the “Database” class which is similar to the start() method.

See the following method structure:

Overall Structure:

Environment Setup

1. Go to the “Developer Console” and go to the “Select New” file. Then, choose “Apex Class” (Apex Class is saved with .apxc extension).

2. You can give the class name after clicking on “Apex Class”. Then, click “Ok”.

3. After writing the class, you can execute it by creating an instance of it. We can write it in the “Anonymous Window”.

Application 1: Updation

Let’s write a “Batch Class” on the Salesforce standard object campaign to update the “Campaign Name” to “LinuxHint Camp1” if the status is “Planned”.

global class BatchExample1 implements Database.Batchable<sObject> {

 

  global Database.QueryLocator start(Database.BatchableContext BC)

  {

    // Write the SOQL Query on Campaign object

    // to get the records with Status - 'Planned'

    return Database.getQueryLocator('SELECT Name, Status FROM Campaign WHERE Status=\'Planned\' order by Name');

  }

 

  global void execute(Database.BatchableContext BC, List<Campaign> campList)

  {

    // Iterate the Campaign records

    for(Campaign camp_obj : campList) {

 

    if(camp_obj.Status == 'Planned'){

    // Update the Campaign Name

    camp_obj.Name = 'LinuxHint Camp1';

      }

  }

  try {

      // Use update - DML to update the Campaign Name

      update campList;

  } catch(Exception e) {

  System.debug(e);

      }

  }

 

  global void finish(Database.BatchableContext BC)

  {

      //Nothing needed here

  }

  }

Run the class by creating an instance.

BatchExample1 firstexample_1 = new BatchExample1();

Database.executeBatch(firstexample_1);

Explanation:

  1. We write an SOQL Query to fetch the record inside the start() method with the “Planned” status.
  2. Using for loop in the execute() method, we iterate the “Campaign” object and specify the “if” condition to check if the status is “Planned” or not. If it is planned, we update the “Campaign Name” to “LinuxHint Camp1”. We use the “update” DML to update the records under the try block.

Check:

We can check if the batch is processed without error under the “Apex Jobs”. Search for it in “Quick Find”.

2. To check for your “Batch” class, we can see that the “Batches Processed” is 1 and “Failures” are 0.

3. Go to the “Campaign Tab” and check if the “Campaign Name” is updated or not.

There is only one record with a “Planned” status. The “Campaign Name” is updated to “LinuxHint Camp1”.

Application 2: Deletion

Let’s write a “Batch Class” on the Salesforce standard object which is “Campaign” to delete one record.

Global class BatchExample2 Implements Database.batchable<sobject>{

 

  global Database.QueryLocator start(Database.BatchableContext BC){

  // SOQL query to return one record from the Campaign object

  return Database.getQueryLocator('select Id from Campaign limit 1');

  }

  global void execute(Database.BatchableContext BC,List<Campaign> scope){

    // delete DML

    delete scope;

 

  }

  global void finish(Database.BatchableContext BC){

     // No need to do anything here.

  }

}

Run the class by creating an instance.

BatchExample2 example_2 = new BatchExample2();

Database.executeBatch(example_2);

Explanation:

  1. We write an SOQL Query inside the start() method to fetch only one record from the “Campaign” object.
  2. We use the “delete” DML in the execute() method to delete that record. You can also apply a try block around the delete DML.

Check:

We can check the deleted records under the “Recycle Bin”. Go to the “App Launcher” and check for it.

You can see one that record is deleted from the “Campaign” object.

Application 3: Insertion

Let’s write a “Batch Class” on the Salesforce standard object which is “Account” to insert one record.

global class BatchExample3 implements Database.Batchable<sObject> {

 

  global Database.QueryLocator start(Database.BatchableContext BC) {

   // SOQL query to return only one record from the Account object

   return Database.getQueryLocator('SELECT Id,Name FROM Account limit 1');

  }

 

  global void execute(Database.BatchableContext BC, List<Account> scope) {

 

  // Create List of type - Account

  List<Account> aList = new List<Account>();

 

  // Create object for Account

  Account anew= new Account();

 

  // Set the field with value

  anew.Name='LinuxHint record';

 

  // Add the object (instance) to the list

  aList.add(anew);

 

  //insert DML

  insert aList;

 

 }

  global void finish(Database.BatchableContext BC) {

  // No need to do here

  }

}

Run the class by creating an instance.

BatchExample3 example_3 = new BatchExample3();

Database.executeBatch(example_3);

Explanation:

  1. We write an SOQL Query inside the start() method to fetch only one record from the “Account” object.
  2. We create a list of “Account type” and create one “Account instance” in the execute() method. After that, we assign the “Account Name” to “Linuxhint record” and add the instance to the apex list collection. Finally, we use the “insert” DML to insert this record in the account.

Check:

Go to “Account” and search for the record. You can find it there.

Click on “Account Name” to open the record with details.

Conclusion

We now learned how to do the mass DML operations like insert, update, and delete with Batch Apex in Salesforce. Batch Apex is an Asynchronous process in which each process is run on a different thread. It processes the data batch by batch and has 3 steps while doing this operation. By default, the Batch size is 200 but we can extend it up to 2000 in which the minimum size is 1. We utilized the “Campaign” and “Account” standard objects to do the DML operations.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain