We often came across situations in apex where we are required to calculate aggregate data but we have a limitation of 50000 records at a time so for these situations, we can use Batch apex and to aggregate data, we can take help by using Database. Stateful. Database.Statefull is used in batch apex to aggregate data irrespective of batch size ie.how many records are being traversed at a time in the list of scope for apex. Example of database.statefull is as follows:
global class exampleForStateful implements Database.Batchable, Database.Stateful{ global map<String,set> userIdVsListOfAccountIds = new map<string,set>(); global Database.QueryLocator start(Database.BatchableContext BC) { String query = ‘select id,variable1,variable2,variable3 from account where variable1 !=null’; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List scope){ for(account obj: scope){ if(obj.variable1!=null){ system.debug(‘In Loop’); set relatedAccountIds = new set(); if(userIdVsListOfAccountIds.keyset().contains(obj.variable1)) { relatedAccountIds = userIdVsListOfAccountIds.get(obj.variable1); relatedAccountIds.add(obj.id); userIdVsListOfAccountIds.put(obj.variable1,relatedAccountIds); } else { relatedAccountIds.add(obj.id); userIdVsListOfAccountIds.put(obj.variable1,relatedAccountIds); } } } } global void finish(Database.BatchableContext BC) { /*userIdVsListOfAccountIds : this map now contains all the records irrespective of batch size if database.stateful is not used then we will not get the complete map with all data but will get data as per no. of times execute method is called.*/ }
In this code, if we want to make a complete map of variable1 V/s set<id> for all related accounts then the use of database.stateful we help in this scenario.Here the map contains a map of all variable1 and its related account Ids in sets and here the data can be as per batch limits, not limited to 50000 records a per SOQL query. Thanks