Activity Forums Salesforce® Discussions Explain the use of Database.Stateful in salesforce?

  • Nikita

    Member
    September 19, 2019 at 12:33 pm

    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 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.

    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.

Popular Salesforce Blogs

Popular Salesforce Videos