Database.Batchable Interface – Data Manipulation Language (DML) – Salesforce Certified Platform Developer I Study Guide

5.4 Database.Batchable Interface

Batchable Apex in Salesforce is an approach to process large volumes of data in smaller, manageable chunks or batches. It enables you to break down the data processing into multiple iterations, each handling a subset of the total data. This approach helps you stay within Salesforce’s governor limits and ensures efficient processing of large datasets.

To use it you need to write an Apex class that implements the Database.Batchable interface and then invoke the class programmatically. The Database.Batchable interface contains three methods that developers need to implement: start(), execute(), and finish(). The start() method is called at the beginning of the batch job and returns a Database.QueryLocator object that identifies the scope of the data to be processed. The execute() method processes each batch of records returned by the start() method, and the finish() method is called after all batches are processed.

The maximum batch size is 200 now and can be specified using Database.executeBatch() method.

Here’s a simple example of the Batch Apex class structure in Salesforce. This class is designed to process leads conversion.

Step 1: Create the class LeadConversionBatch and save

global class LeadConversionBatch implements Database.Batchable<SObject> {

global Database.QueryLocator start(Database.BatchableContext context)

{

String query = ‘SELECT Id, FirstName, LastName, Email, Company ‘ + ‘FROM Lead WHERE IsConverted = false AND Status = \’Qualified\”; return Database.getQueryLocator(query);

}

global void execute(Database.BatchableContext context, List<Lead> leadRecords) {

List<Database.LeadConvert> leadsToConvert = new List<Database.LeadConvert>();

for (Lead lead : leadRecords) {

Database.LeadConvert lc = new Database.LeadConvert();

lc.setLeadId(lead.Id);

lc.setConvertedStatus(‘Qualified’); // Use appropriate status

leadsToConvert.add(lc);

}

if (!leadsToConvert.isEmpty()) {

try {

List<Database.LeadConvertResult> lcr = Database.convertLead(leadsToConvert);

  • Process the results if needed } catch (Exception e) {
  • Handle any exceptions

}

}

}

global void finish(Database.BatchableContext context) { // Any post-processing logic can go here

}

}

Step 2: Open the anonymous window

Step 3: Insure you have already some leads in your org converted

Step 4: Print the Batch Job ID to the debug log in the Developer Console.

// Execute the batch job immediately

LeadConversionBatch leadBatch = new LeadConversionBatch(); String jobId = Database.executeBatch(leadBatch);

  • Print the job ID for reference System.debug(‘Batch Job ID: ‘ + jobId);

•\ The start method is the starting point of the batch job. It returns a

Database.QueryLocator that defines the initial set of records to be

processed. In this case, it selects leads that meet specific criteria: those

with the IsConverted field set to false and Status set to ‘Qualified’.

•\ The execute method processes a batch of leads retrieved by the start

method. This method is called for each batch of records.

It creates a list of Database.LeadConvert objects for each lead in the batch. For each lead, it sets the lead ID and the converted status to ‘Qualified’.

It then attempts to convert these leads using the Database. convertLead() method. The method includes error handling to catch any exceptions that might occur during the conversion process.

•\ The finish method is called after all batches have been processed. In

this implementation, it’s left empty but can include any additional

logic that should run after the batch job is complete.

•\ The purpose of this Batch Apex class is to convert qualified, unconverted

leads into contacts, accounts, and potentially opportunities in batches.

By processing leads in batches, it can handle large volumes of data more

efficiently and comply with Salesforce’s governor limits.

•\ The class doesn’t directly create Contact or Account objects. Instead, it uses Salesforce’s standard lead conversion process (Database. convertLead()), which automatically creates these records based on the lead information.

Keep in mind that executing batch jobs directly in an anonymous window is typically done for testing purposes. In a production environment, it’s more common to schedule batch jobs using the Salesforce UI or in a separate Apex ScheduledApex class.