You need to sign in to do that
Don't have an account?
batch job
Hello everyone, can you help me?
I need to add Author name wich is located in Author Id object into Book object and after that i need to send email. Both fields are in junction object AuthorToBook. Explain me whats wrong with my code?
public class BatchUpdateBookAuthors implements Database.Batchable<sObject>, Database.Stateful {
public Integer recordsProcessed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT ID, Author__c FROM Book__c WHERE Author__c = null' +
'SELECT ID, Author__c, Book__c (SELECT Id FROM Author__c) FROM AuthorToBook__c'
);
}
public void execute(Database.BatchableContext bc, List<AuthorToBook__c> scope){
// process each batch of records
List<Book__c> books = new List<Book__c>();
for (AuthorToBook__c authors : scope) {
for (Book__c book : books) {
book.Author__c = authors.Author__c;
books.add(book);
recordsProcessed = recordsProcessed + 1;
}
}
update books;
}
public void finish(Database.BatchableContext bc){
System.debug(recordsProcessed + ' records processed!');
AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,
JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :bc.getJobId()];
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'olga.luckina@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Books';
message.plainTextBody = 'Books are updated';
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if (results[0].success) {
System.debug('The email was sent successfully.');
} else {
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}
Hi,
there is no data inside books i.e List<Book__c> books = new List<Book__c>();
so you no need to iterate over books i.e
You can correct it like the below
Please mark it as the Best Answer if it helps you.
Thank You