Skip to content

Instantly share code, notes, and snippets.

@jongpie
Last active February 20, 2022 13:55
Show Gist options
  • Save jongpie/dbd19692808dfa9cf72286deafe09b02 to your computer and use it in GitHub Desktop.
Save jongpie/dbd19692808dfa9cf72286deafe09b02 to your computer and use it in GitHub Desktop.
Example Apex batch job that runs multiple queries for different SObject Types
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