I have a map variable that I am trying to pass into a batch class. This variable was created and populated in another batch class (which is why I can't just create it in the Start()
method of the second batch class).
The first batch class implments Database.Stateful
, in order to preserve the values I store in the map variable. Then, in the Finish()
method, I call the second batch class, passing the map variable, like so:
Database.executeBatch(new BatchClass(mapVariable));
The problem I'm running into is that I can't get the second batch class to recognize that I've passed this map to it. I've tried using the this.variable
assignment in the constructor class without being clear on its purpose, to no avail. Here's an idea of what that second batch class looks like now:
global class BatchClass implements Database.Batchable<sObject>{
String query = '[some SOQL query]';
global ClientMetrics_Stage6BatchClass(map<key, value> mapVariable) {
this.mapVariable = mapVariable;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope) {
methodWhichUsesMapVariable();
}
global void finish(Database.BatchableContext BC) {}
In this format, the batch class doesn't recognize mapVariable
(says it does not exist). I've also tried making this batch class stateful, as well as declaring the mapVariable separately prior to the start() method, similar to the query
variable, which I thought might be necessary to do the this.mapVariable
assignment.
How can I make it so this Batch class can use the map variable I'm trying to pass to it? Thanks for your help and Merry Xmas/happy holidays!
EDIT:
So I got it to work (or at least save without error) by declaring the map variable before the start()
method, then assigning the passed variable to it, like so:
public static map<string, decimal> mapVariable = new map<string, decimal>();
global ClientMetrics_Stage6BatchClass(Map<string, decimal> sameMapVariableWithDiffName) {
mapVariable = sameMapVariableWithDiffName;
}
The interesting thing is, it didn't work until I specifically made the declared variable a static
variable. My understanding is that even though I made this batch class stateful
, static variables are reset with every batch. I don't know if this means I'm going to lose the map values after the first batch, but I'm about to find out!
If anyone knows why I could only get this to work by declaring the map static, I'd love to learn the reason!