+ Start a Discussion

Another Batch Apex issue: class members.

I wrote somthing like this to check the way class fields are

behaving in Batch apex:

This code counts number of times execute method was called

For my surprise I saw that I get only 1 in the debug logs!



global class To_Bach implements Batchable{


global Integer _i;


global Bach(){

   _i = 0;





global void execute(){


   System.debug('times visited '+i);





SO! How thies field behave?

What am I missing?



By default each execution of a batch apex job is considered a discrete transaction. To maintain state across transactions you have to declare the class as database.stateful. 





global class To_Bach implements Database.Batchable<sObject>, Database.Stateful{

   global integer i;
   global final string query;
global To_Bach(string q){
i = 0;
query = q; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){
system.debug('times visited: '+i); } global void finish(Database.BatchableContext BC){ } }