You need to sign in to do that
Don't have an account?
Rishabh Patel 1
Create Batch Apex to update multiple objects
Hello, I already have a Schedule apex, that works on 3 objects to do a basic Query and update. I wanted to make this class batch. But unable to add multiple objects in Batch apex and loop around them .
Here is how my Schedule apex looks like
global class scheduleWorkday implements Schedulable { global void execute(SchedulableContext ctx) { //Get Accounts List<Account> getbdayaccount = [Select ID, Name, Address from Account where State= CT]; if(!getbdayaccount .isEmpty()) { for(Account a : getbdayaccount ) { a.name = 'Test'; a.State= 'NJ'; } update getbdayaccount ; } //get Leads List<Lead> getPreApprovalFollow = [Select ID, Name, State, LeadSource from Lead where State = 'CT' ]; if(!getPreApprovalFollow .isEmpty()) { for(Lead l: getPreApprovalFollow ) { l.LeadSource = 'Referral'; l.State = 'NJ'; } update getPreApprovalFollow ; } //get Opportunities List<Opportunity> getopps = [Select Id, CloseDate, State from Lead where State = 'CT']; if(!getopps.isEmpty()){ for(Opportunity o : getopps){ o.CloseDate = Date.Today(); o.State = 'CT'; } update get opps; } } }
I tried making batch apex something like this -
global class LeadProcessor implements Database.Batchable <SObject> { //START METHOD global Database.QueryLocator start(Database.BatchableContext bc){ String Query='Select id,LeadSource, State from Lead where state = 'CT''; return Database.getQueryLocator(Query); } //EXECUTE METHOD global void execute(Database.BatchableContext bc, List<Lead> scope){ for(Lead l: scope){ l.LeadSource='Referral'; l.State = 'NJ'; } update scope; } //FINISH METHOD global void finish(Database.BatchableContext bc){ } }
How can I change this batch apex to return multiple queries and update them .
Thank you
Since the 3 queries are independent of each other, I recommend you to make 3 batch classes - 1 batch for each object. Do you have any good business reason to keep them into one class? You should apply OOPS here and not club all the different functionalities into one class.
Another point to note is that the start method cannot return you list of records from 3 unrelated objects. So you have no way to get this sorted with just one batch class.