State Management In Batch Apex in Salesforce
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. This is useful for counting or summarizing records as they're processed. For 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.
If you do not specify Database.Stateful, all member variables in the interface methods are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
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){
}
}
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. This is useful for counting or summarizing records as they're processed. For 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.
If you do not specify Database.Stateful, all member variables in the interface methods are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
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){
}
}