How can we maintain state across batches in apex

INTRODUCTION

Today, we will discuss the Database.Stateful interface, which plays a crucial role in maintaining state across batch call methods. When working with the Database.Stateful interface, instance member variables of a class retain their values between transactions of the execute() method, while static variables do not support this feature in the context of a Batch class.

For instance, suppose we have a task that involves counting the number of records processed in the database. In such cases, we must utilize the Database.Stateful interface.

Let’s explore a simple example that demonstrates the use of Database.Stateful. In this program, we will count the number of times the execute() function is executed and display its value in the finish() function.

Batch Class Code

global class BatchWithIncrementor implements Database.Batchable, Database.Stateful {
    global integer count = 0;
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Name FROM Account';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List accList) {
        count= count+1;
        System.debug('@@@@execute'+ count);
    }
    global void finish(Database.BatchableContext BC) {
        System.debug('@@@@@@finish'+count); //return the last value incremented by execute() function
    }
}

I hope you now have a clear understanding of how to utilize the Database.Stateful interface in a Batch class.

Thank you, and happy coding!