我试图在可批处理类的 finish() 方法中使用全局 Map 变量,但它的行为很奇怪,我确信我做错了什么,但不知道哪里错了。 在下面的简化代码中,第一条调试消息按预期输出 map 的实际大小。但是,finish() 方法中的调试消息输出 0,作为同一映射的大小。看起来 map 在途中的某个地方被重新实例化,但我不确定在哪里。
global class MySchedulableClass implements Database.Batchable<sObject> {
global map<string,string> StringStringMap;
global string query;
global MySchedulableClass(){
if (query == null)
query = 'Select id, name From Contact LIMIT 20';
if (StringStringMap == null){
StringStringMap = new map<string,string>();
}
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<sObject> scope){
for(Sobject s: scope) {
con = (Contact) s;
StringStringMap.put(s.id, s.name);
}
system.debug('Map size:' + StringStringMap.size());
}
global void finish(Database.BatchableContext BC){
system.debug('Map size:' + StringStringMap.size());
}
}
最佳答案
如果您想在批处理运行期间保留信息,请查看 Database.Stateful。请参阅Using State in Batch Apex 。它涵盖了全局变量不持久的原因。
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions.
关于salesforce - 为什么 Apex Schedulable 类中的全局 Map 不包含任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070332/