Salesforce Batch Class for Aggregate Queries

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> {
  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 &amp;&amp; !results.isEmpty() &amp;&amp; index &lt; results.size(); 
  }    

  global AggregateResult next(){        
    return results[index++];            
  }       
}
</aggregateresult>


AggregateResultIterable




global class AggregateResultIterable implements Iterable<aggregateresult> {
  private String query;

  global AggregateResultIterable(String soql){
    query = soql;
  }

  global Iterator<aggregateresult> Iterator(){
    return new AggregateResultIterator(query);
  }
}
</aggregateresult></aggregateresult>




global class BatchSummariseAccountSummary implements Database.Batchable<aggregateresult>{
    global Iterable<aggregateresult> 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<sobject> scope){   
         List<account> lstAccount=new List<account>();
         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){
         
    }
}
</account></account></sobject></aggregateresult></aggregateresult>


Note: After save whole code you can run batch from Developer console with below code


BatchSummariseAccountSummary  bsas=new BatchSummariseAccountSummary();
database.executebatch(bsas); 



Happy Sharing...

Everyone has their own favorites, so please feel free to share yours in the comments below!

Comments

Popular posts from this blog

User Data Privacy

Tip of the week # 210 : Lightning Input Address with Autocomplete

Tip of the week # 212 : Lightning Datatable hidden gems