Jul 5, 2024
21 Views
Comments Off on Apex Batch – Use of Interface Database.Stateful in Batch Class
0 0

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

Written by

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.

Article Categories:
Salesforce Tutorial
Priya Singh
https://thestarbiznews.com/

Expertise: Technology Trends, Startups, Digital Disruption Bio: Priya Singh is a tech-savvy millennial with a finger on the pulse of the ever-evolving digital landscape. A graduate of Stanford's Computer Science program and a former engineer at a Silicon Valley giant, Priya has a deep understanding of the technologies shaping our future. Her passion lies in demystifying complex tech jargon and exploring the disruptive potential of emerging trends, making her articles essential reading for anyone who wants to stay ahead of the curve. When not scouring the web for the latest tech tidbits, Priya enjoys traveling to off-the-beaten-path destinations and immersing herself in diverse cultures, always seeking new inspiration and insights.