In batch apex we want to maintain flag to keep track on records that has been processed before to avoid duplicate conversion in case batch fails half the route and we have to execute that again.
Below is my code. In if condition I am checking for the flag value not true and as soon as it enters that if I am changing that value to true and updating ctb. This is not throwing any error but not updating checkbox field.
global class caseToBe implements Database.Batchable<sObject>, Database.Stateful {
Integer totalRecordsInserted = 0;
Integer totalRecordsFailed = 0;
global Iterable<sObject> start(database.BatchableContext BC)
{
system.debug('Start Called');
return Database.getQueryLocator([select Name,Accounting_Date__c,Balance_Due__c,Temp__c,Agency_Name__c from CaseToBe__c where Name != NULL]);
}
global void execute(Database.BatchableContext BC, List<CaseToBe__c> scope)
{
system.debug('Execute Called');
List<Case> ToInsertCaseList = new List<Case>();
for(CaseToBe__c ctb : scope)
if(ctb.converted__c != True){
ctb.converted__c = True;
update ctb;
{
system.debug('In Loop');
ToInsertCaseList.add(
new case(
Account_Number__c = ctb.Name,
Balance_Due__c = ctb.Balance_Due__c,
AccountId = ctb.Agency_Name__c,
Status = 'Working',
Origin = 'Web'
));
}
}
insert ToInsertCaseList;
}
global void finish(database.BatchableContext BC)
{
system.debug('Finish Called');
AsyncApexJob a = [Select Id, Status, NumberOfErrors,JobItemsProcessed, TotalJobItems, CreatedBy.Email
from AsyncApexJob where Id =
:BC.getJobId()];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.Createdby.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex sharing Recalculation' + a.Status);
mail.setplainTextBody('The Batch Apex Job has been processed' + a.TotalJobItems + 'batches with' + a.NumberOfErrors + 'failures');
Messaging.sendemail(new Messaging.SingleEmailMessage[] {mail});
}
}
update ctb;
and addupdate scope;
after the loop. You can include this your own answer.