Salesforce Batch Class for Aggregate Queries
Salesforce Batch Class for Aggregate Queries
Recently, I got one requirement, in which I have to use aggregate queries in batch apex class.
My requirement was totally different. For blog I'm using Account and Contact as a example.
Let us have a walkthrough how to set up Push Notification.
Step 1. Create the Notification Route.
- AggregateResultIterator
 - AggregateResultIterable
 - Implementing to Database.Batchable
 - Iterable
start method of Batch Class  
AggregateResultIterator
global class AggregateResultIterator implements Iterator {
  AggregateResult [] results {get;set;}
  // tracks which result item is returned
  Integer index {get; set;} 
       
  global AggregateResultIterator(String query) {
    index = 0;
    results = Database.query(query);            
  } 
  global boolean hasNext(){ 
    return results != null && !results.isEmpty() && index < results.size(); 
  }    
  global AggregateResult next(){        
    return results[index++];            
  }       
}
  
AggregateResultIterable
global class AggregateResultIterable implements Iterable {
  private String query;
  global AggregateResultIterable(String soql){
    query = soql;
  }
  global Iterator Iterator(){
    return new AggregateResultIterator(query);
  }
}
   
global class BatchSummariseAccountSummary implements Database.Batchable{
    global Iterable start(Database.BatchableContext BC){
        return new AggregateResultIterable('Select Count(Id) cactive,AccountId  From Contact Where AccountId != null GROUP BY AccountId ORDER BY AccountId DESC');
    }
    global void execute(Database.BatchableContext BC, List scope){   
         List lstAccount=new List();
         for(sObject sObj : scope) {
          AggregateResult ar = (AggregateResult)sObj;
          Account acc=new Account();
          //ContactsCount__c is custom field on Account
          acc.ContactsCount__c=Decimal.valueOf(ar.get('cactive')+'')
          lstAccount.add(asum);          
        }
        if(!lstAccount.isEmpty()){                    
            update lstAccount;
        }
    } 
    global void finish(Database.BatchableContext BC){
         
    }
}
      
Note: After save whole code you can run batch from Developer console with below code
BatchSummariseAccountSummary  bsas=new BatchSummariseAccountSummary();
database.executebatch(bsas); 
 

Comments
Post a Comment