Firstly, we must understand that if we want to use Batch Apex, we must write an Apex Class that implements the Salesforce-provided interface Database. Batchable and then invoke the class programmatically. To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.

In this article, we delve into the powerful features of Database. Stateful in Batch Apex. Understanding Database. Stateful is essential for maintaining state across batch job executions, allowing developers to preserve instance variables and make more sophisticated, state-aware batch processes.

Syntax for Batch:

global class BatchName implements Database.Batchable{}

Methods of Batch Class:

global (Database.QueryLocator | Iterable) start (Database.BatchableContext bc) {
 //Here we will add the query and return the result to execute method
}

global void execute (Database.BatchableContext BC, list<P>){
 //Logic must be here
}

global void finish (Database.BatchableContext BC){
 //after processing of all batches this method will be called. We can write any code inside it. Like if want to send email to all the records which are created or updated in the execute method.
}

Also Read: How To Create A Custom Report Type In Salesforce?

Implementing the Database.Batchable Interface

Example:

global class BatchAccountUpdate implements Database.Batchable{
    String query = 'Select Name from Account WHERE Name! = null AND (Name = \'Virendra Company\' OR Name = \'Virendra Sharma\') ';
    global Database.QueryLocator start (Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
        return Database.getQueryLocator(query);
    }
    
    global void execute (Database.BatchableContext bc, List records) {
        // process each batch of records
        for (Account acc : records){
            acc.Name = acc.Name + '  Updated';
        }
        update records;
    }
    
    global void finish (Database.BatchableContext bc){
        // execute any post-processing operations, Calling batch class.
        BatchUpdateAccountRelatedContacts b = new BatchUpdateAccountRelatedContacts();
        Database.executeBatch(b, 200);
    }    
}
database stateful

Database.Stateful

The following sample class finds all account records that are passed in by the start() method using a QueryLocator and updates the associated contacts with their account’s mailing address. Finally, it sends off an email with the results of the bulk job and, since we are using Database.Stateful to track state, the number of records updated.

database stateful code
database stateful code

Example:

hire salesforce developers

Database.AllowsCallout

Database.AllowsCallout in Batch helps in integrating Salesforce with an external server. To use a callout in batch Apex, we must use an interface Database.AllowsCallouts in the class definition of batch class.

Syntax:

global class SearchAndReplace implements Database.Batchable, Database.AllowsCallouts{}

Example:
Here, I am integrating the Opportunity object with Razorsync.com
/*
Get service request from razorsync and update it into the salesforce
*/

global class Batch_SR_RazorSyncAPI implements Database.Batchable, Database.AllowsCallouts{
    global Database.QueryLocator start (Database.BatchableContext BC){
        String query = 'SELECT Id, Razorsync_Service_Request_Id__c FROM Opportunity WHERE Razorsync_Service_Request_Id__c != null AND Razorsync_Job_Status__c != \'Job Done\' AND RazorSync_Status__c = \'Success\'';
        return Database.getQueryLocator(query);
    }
   
    global void execute (Database.BatchableContext BC, List scope){
        String StatusId = '';
        for (Opportunity s : scope){
            //get ServiceRequest
            System.debug(s.Id);
            Http http1 = new Http();
            HttpRequest request1 = new HttpRequest();
            request1.setEndpoint('https://DomainName.0.razorsync.com/ApiService.svc/ServiceRequest/'+ s.Razorsync_Service_Request_Id__c);
            request1.setMethod('GET');
            request1.setHeader('Content-Type', 'application/json');
            request1.setHeader('Host', 'DomainName.0.razorsync.com');
            request1.setHeader('Content-Length', '0');
            request1.setHeader('Connection', 'Keep-Alive');
            request1.setHeader('ServerName', 'DomainServerName');
            request1.setHeader('Token', 'XXXXXXXXXXXXXXXXXXXXXXX');
            
            HttpResponse response1 = http1.send(request1);
            
            if(response1.getStatusCode() == 200) {
                StatusId = '';
                JSONParser parser = JSON.createParser(response1.getBody());
                while(parser.nextToken() != null) {
                    if( (parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'StatusId') || Test.isRunningTest()) {
                        parser.nextToken();
                        StatusId = parser.getText();
                    }
                }
                System.debug(StatusId);
                if(StatusId == String.valueOf(1) || Test.isRunningTest()){
                    s.Razorsync_Job_Status__c = 'Job Done';
                    s.StageName = 'Closed Won';
                }else{
                    s.Razorsync_Job_Status__c = 'Working';
                }
            }
        }
        update scope;
    }
    global void finish (Database.BatchableContext BC){
    }
}

Also Read: Benefits of Salesforce Commerce Cloud and How To Call Flows From Apex In Salesforce

Conclusion

Using Database.Stateful in Batch Apex within Salesforce allows for preserving state across different execution methods in a batch job. This is crucial for scenarios where complex data processing is required, and the state must be retained between batch chunks.

By implementing Database.Stateful, developers can ensure data consistency and manage large data sets effectively. However, it’s important to use this feature judiciously to avoid excessive memory consumption and potential performance issues.

Best practices include keeping state variables minimal and focusing on essential data, thus making Database.Stateful a powerful tool for complex, state-dependent batch processing in Salesforce.

For further assistance with a salesforce project, hire us as your salesforce consultant and reap the benefits.

Avatar photo
Author

With a decade of experience in eCommerce technologies and CRM solutions, Virendra has been assisting businesses across the globe to harness the capabilities of information technology by developing, maintaining, and improving clients’ IT infrastructure and applications. A leader in his own rights his teammates see him as an avid researcher and a tech evangelist. To know how the team Virendra can assist your business to adopt modern technologies to simplify business processes and enhance productivity. Let’s Talk.

whatsapp