Last active
April 9, 2025 12:08
-
-
Save jongpie/dbd19692808dfa9cf72286deafe09b02 to your computer and use it in GitHub Desktop.
Example Apex batch job that runs multiple queries for different SObject Types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public without sharing class MultiQueryExampleBatchJob implements Database.Batchable<SObject>, Database.Stateful { | |
private Schema.SObjectType currentSObjectType; | |
// Add any SObject Types here if you want the batch job to query them | |
private List<Schema.SObjectType> sobjectTypes = new List<Schema.SObjectType>{ Schema.Account.SObjectType, Schema.Contact.SObjectType }; | |
public Database.QueryLocator start(Database.BatchableContext context) { | |
this.currentSObjectType = this.sobjectTypes.remove(0); | |
return this.getQueryLocator(); | |
} | |
public void execute(Database.BatchableContext context, List<Object> scope) { | |
// Add any SObject Types here if you want the batch job to process them | |
switch on this.currentSObjectType.newSObject() { | |
when Account a { | |
this.processAccounts((List<Account>) scope); | |
} | |
when Contact c { | |
this.processContacts((List<Contact>) scope); | |
} | |
} | |
} | |
public void finish(Database.BatchableContext context) { | |
// If there are still any SObjectTypes to process, then restart the batch | |
if (this.sobjectTypes.isEmpty() == false) { | |
Integer batchSize = 2000; | |
Database.executeBatch(this, batchSize); | |
} | |
} | |
private Database.QueryLocator getQueryLocator() { | |
Database.QueryLocator queryLocator; | |
// Add any SObject Types & corresponding QueryLocator here so the batch knows how to query them | |
switch on this.currentSObjectType.newSObject() { | |
when Account a { | |
queryLocator = Database.getQueryLocator([SELECT Id, Name, AccountSource FROM Account]); | |
} | |
when Contact c { | |
queryLocator = Database.getQueryLocator([SELECT Id, FirstName, LastName FROM Contact]); | |
} | |
} | |
if (queryLocator == null) { | |
Exception ex = new IllegalArgumentException(); | |
ex.setMessage('Unsupported SObjectType: ' + this.currentSObjectType); | |
throw ex; | |
} | |
return queryLocator; | |
} | |
private void processAccounts(List<Account> accounts) { | |
// TODO - add your logic for whatever you want to do to the accounts | |
} | |
private void processContacts(List<Contact> contacts) { | |
// TODO - add your logic for whatever you want to do to the contacts | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment