Monday, 2 September 2019

Custom Iterator (Iterable) in Batch Apex

1.If you use an iterable the governor limit for the total number of records retrieved by soql queries is still enforced.

2.if your code accesses external objects and is used in batch Apex, use iterable<sobject> instead of Database.QueryLocator.

global class CustomIterable implements Iterator<Contact>{

  List<Contact> con {get;set;}
   Integer i {get;set;}
 
   public CustomIterable(){
      con = [select Id,LastName From Contact LIMIT 5];
  i=0;
   }
     // This is Iterator interface hasNext() method, it will
// return true if the list 'con' contains records else it
// will return false;

   global boolean hasNext(){
      if(i>=con.size()){
    return false;
  }else{
    return true;
  }
   }
 
   // This is Iterator interface next() method, it will keep on
   // returning next element on the list until integer i reaches 5
   // and 5 in if loop is the size of the list returned by soql query
   // in above code
 
   global Contact next(){
     if(i==5){return null;}
i++;
return con[i-1];
   }
 
}

Note :
If your code accesses external objects and used in batch Apex, use Iterable<sObject> instead of Database.QueryLocator.

In Batch Apex , the start method return a Database.QueryLocator ,but you can return an Iterable.

global class batchClass implements Database.batchable<Contact>{
 global Iterable<Contact> start(Database.batchableContext info){
   return new CustomIterable();
 }
 global void execute(Database.batchableContext info,List<Contact> scope){
    List<Contact> conToUpdate = new List<Contact>();
for (Contact c :scope){
   c.LastName='Test123';
   conToUpdate.add(c);
}
update conToUpdate;
 }
 global void finish(Database.batchableContext info){

 }
}

Note :
1. Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.

2. Use iterable object when you have complex criteria to process the records.

No comments:

Post a Comment