0

I have a batch process which loops trough records to count different statuses per user. I store these in a map. When the Batch is done I want to update the results on an aggregated object.

How do I pass the set and maps to the finish method to update the values on the aggregated object or do I need to create a sub batch process for this.

I have the following. When I do a system debug in the finish method I do not get results

    global void execute(Database.BatchableContext bc,List<Workethic__c> scope)
    { 
        if(scope.size() > 0)
        {
            for(Workethic__c workEts : scope){
                userIds.add(workEts.User__c);
                if(earlyCount.containsKey(workEts.User__c) && workEts.WorkethicStatus__c == 'Early'){
                    earlyCount.put(workEts.User__c,earlyCount.get(workEts.User__c)+1);
                }else if (workEts.WorkethicStatus__c == 'Early'){
                    earlyCount.put(workEts.User__c,1);   
                }
                if(lateCount.containsKey(workEts.User__c) && workEts.WorkethicStatus__c == 'Late'){
                    lateCount.put(workEts.User__c,lateCount.get(workEts.User__c)+1);
                }else if ( workEts.WorkethicStatus__c == 'Late'){
                    lateCount.put(workEts.User__c,1);
                }              
            }
        }
       
    }
    
    global void finish(Database.BatchableContext bc)
    {
       System.debug('earlyCount Map : '+ earlyCount); 
        System.debug('userIds Finishmethod: '+ userIds); 
        List<AggregatedResult__c> aggResults = [select id, Early_TotalScore__c  from AggregatedResult__c where id IN :userIds]; 
.. Update List
    }
3
  • 2
    You can use Database.Stateful interface and create a instance variable to retain the map or list and use it in finish method. Commented Jul 14, 2022 at 11:23
  • @BalwinderKumar Thanks!, so simple. Can you add this as an answer other wise I will delete the question
    – Thomas
    Commented Jul 14, 2022 at 11:38
  • 1
    note that Database.Stateful consumes heap so if your maps are huge (12MB) , you may have an issue - normally this is not a problem
    – cropredy
    Commented Jul 14, 2022 at 14:56

1 Answer 1

2

Please implement Database.Stateful interface and create instance variable in the class to hold the map or list. Same can be used in finish method.

Salesforce Developer Guide around Database.Stateful interface usage.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .