Activity › Forums › Salesforce® Discussions › Explain the use of Database.Stateful in salesforce?
-
Explain the use of Database.Stateful in salesforce?
Posted by Laveena on September 19, 2019 at 12:25 PMExplain the use of Database.Stateful in salesforce?
Nikita replied 6 years, 8 months ago 2 Members · 1 Reply -
1 Reply
-
Hi Laveena,
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions. Maintaining state is useful for counting or summarizing records as they’re processedFor example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed.
Let’s take an example here
global class SummarizeAccountTotal implements Database.Batchable<sObject>, Database.Stateful{ global final String Query; global integer Summary; global SummarizeAccountTotal(String q){Query=q; Summary = 0; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute( Database.BatchableContext BC, List<sObject> scope){ for(sObject s : scope){ Summary = Integer.valueOf(s.get('total__c'))+Summary; } } global void finish(Database.BatchableContext BC){ } }
Log In to reply.