Apex Batch

Apex Batch - Use of Interface Database.Stateful in Batch Class

Hello guys,

Today, we will talk about interface named as Database.Stateful, it is used when we want to maintain the state across the batch call methods. In interface Database.Stateful, the instance member variable  of class maintain their values between transactions of execute()  method while the static variable does not support this feature in Batch class.  For example, our task is to count the number of records processed in the database then we must need to use the Database.Stateful interface.

Let see one simple example on Database.Stateful, in this program we are going to count the number of times an execute() function runs and print its value in 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
    }
}

Hope you will get an idea that how we can use Database.Useful in Batch class.

Thanks.

Happy Coding.

Popular Salesforce Blogs