Why we use Database.stateful in Batch Apex Salesforce

by Rijwan Mohmmed
why-we-use-database-stateful-in-batch-apex-salesforce

In the Batch apex, each execution gets a fresh copy of variables and objects. because batch class by default is stateless. If you try to use old execution values in new execution, it can’t be possible. that means static variables don’t retain their values.

So if you want to use such variables who retain their values and use them in execute and finish method we need to implement Database. stateful in the class definition.

One more reason to use this interface is to use variables in the finish method and run the method/logic accordingly.

StatefulBatchApex.cls :

global class StatefulBatchApex implements Database.Batchable<sObject>, Database.Stateful{
     
    global integer totalaccountUpdated = 0;
     
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name From Account';
        return Database.getQueryLocator(soqlQuery);
    }
     
    global void execute(Database.BatchableContext bc, List<Account> scope){
        List<Account> accList = new List<Account>();
        for (Account acc : scope){
	   if(!acc.name.contains('Update')){
	       acc.name = acc.name + ' Update';
	       accList.add(acc);
               totalaccountUpdated++;
            }
        }
		
	if(!accList.isEmpty()){
	    Update accList;
	}
    }
     
    global void finish(Database.BatchableContext bc){
         System.debug('No. of Account updated ==> '  + totalaccountUpdated);
    }
}

Calling Batch Apex :

StatefulBatchApex batchApex = new StatefulBatchApex();
Id batchJobId = Database.executebatch(batchApex, 100);
What’s your Reaction?
+1
3
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

1 comment

Lavon November 11, 2021 - 5:22 pm

Great article. I am experiencing many of these issues as well..

Reply

Leave a Comment