Sub topic 3
Bulkifying DML and Choosing an Apex Approach
This chapter assumes basic Apex syntax, collections, SObjects, try/catch, and Salesforce governor limits.
Bulkifying DML
Bulkification means processing many records with one database operation instead of calling DML inside a loop. Both DML statements and Database methods count against the same DML statement limit. Collect records first, then save the collection once.
List<Contact> contactsToInsert = new List<Contact>();
for (Account account : accounts) {
contactsToInsert.add(new Contact(
LastName = 'Primary',
AccountId = account.Id
));
}
insert contactsToInsert;A DML call inside the loop can exceed limits and performs less efficiently.
Choosing Between Statements and Database Methods
Use a DML statement when the operation should be all-or-nothing and concise error handling is sufficient. A failed statement throws DmlException.
Use a Database method when you need partial success or detailed results. With allOrNone set to false, each input record receives a result object.
List<Database.SaveResult> results =
Database.insert(records, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug('Input ' + i + ' failed: ' +
results[i].getErrors()[0].getMessage());
}
}The result list keeps the same order as the input list, so store or derive enough context to identify each source record.
Advanced Database Options
Database.DMLOptions changes selected DML behavior. For example, this configuration allows string values longer than a field's limit to be truncated and requests partial success.
Database.DMLOptions options = new Database.DMLOptions();
options.allowFieldTruncation = true;
options.optAllOrNone = false;
List<Database.SaveResult> results =
Database.insert(accounts, options);Use truncation only when losing the extra characters is acceptable.
External ID Upserts
upsert inserts a record when its external ID is new and updates the matching record when that ID already exists.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100')
};
List<Database.UpsertResult> results =
Database.upsert(accounts, Account.External_Id__c, false);
if (results[0].isSuccess()) {
System.debug(results[0].isCreated() ? 'Inserted' : 'Updated');
}Savepoints and Rollback
A savepoint marks a transaction position. Database.rollback undoes DML performed after that point in the same transaction.
Savepoint checkpoint = Database.setSavepoint();
try {
insert new Account(Name = 'Acme');
insert new Contact(LastName = 'Smith');
Database.rollback(checkpoint);
} catch (DmlException e) {
Database.rollback(checkpoint);
System.debug(e.getMessage());
}Rollback does not undo external actions such as an already completed callout.
Exercise
Which approach should you use when valid records must be saved even if another record fails?
Show answer
Use a Database method with allOrNone set to false, then inspect each result object.