AfterInsert.OwnUnitOfWork
Gives a Writer its own DML Lib unit of work instead of the shared one. Use it for user mode, sharing, partial success or your own statement order.
Interface
apex
public class AfterInsert {
public interface OwnUnitOfWork {
DML.Committable ownUnitOfWorkOnAfterInsert();
}
}ownUnitOfWorkOnAfterInsert(): called once per chunk, when the handler list is built, even for a handler that is then bypassed. Returns the unit this Writer registers into.
Only a Writer uses it; a Dispatcher ignores it.
Example
apex
public with sharing class ContactWriter implements AfterInsert.Writer, AfterInsert.OwnUnitOfWork {
public DML.Committable ownUnitOfWorkOnAfterInsert() {
return new DML().userMode().identifier('ContactWriter');
}
public Boolean writeOnAfterInsertWhen(TriggerHandler.InsertRecord record) {
return record.isNotNull(Contact.AccountId);
}
public void writeOnAfterInsert(TriggerHandler.InsertRecord record, TriggerHandler.UnitOfWork unitOfWork) {
unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
}
}Good to Know
- Commits at the Writer's turn. The unit commits right after this Writer's Finalizer, when at least one record qualified. Later handlers can query its rows.
- Costs its own statements. It is never merged with the shared unit. Each commit costs at least one DML statement per operation and object type.
- Duplicates throw. Without
combineOnDuplicate(), a secondtoUpdateortoDeleteof the same Id throws at registration. - Partial success hides failures. With
allowPartialSuccess(), failed rows do not throw and never reachTriggerOrchestrator.Logger. Read them withDML.retrieveResultFor('<your identifier>'). - A failed commit is this Writer's error. It is logged under the Writer's name and fails the insert, unless the Writer implements ContinueOnError.
