Passing Parameter to batch apex
Pass in constructor.
public class callNotesbatchcls {
Public PageReference callingMethod()
{
batchNotesInsert shn = new batchNotesInsert('Testing here');
database.executeBatch(shn ); return null;
}
}
batch
global class batchNotesInsert implements Database.Batchable<sObject>, Database.Stateful {
private String strParameter;
public batchNotesInsert(String strParam) {
strParameter = strParam;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = 'select id,Parent.name,Parent.Type,Title,body from note';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Note> scope) {
system.debug('==========check string====='+strParameter);
}
global void finish(Database.BatchableContext BC) {
}
}
Yes Like @Eric and @crop1645 said.
If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values.
If you do not use database.stateful then any changes made to the parameter during the execute method are not persisted across batches and the next execute method will be the original value. You can test this by adding strParameter += '--Added String' and you will see that the debugged value for each execute method is the original value
If we are modifying strParameter
in execute method then still it will have its original value. maintain the updated value in strParameter
we need database.stateful
Note: If you are not modifying strParameter
value in execute method then no need to use database.stateful