The Unit of Work Pattern
By the end of this lesson, you'll be able to:
- Explain what problem the Unit of Work pattern solves
- Describe how it batches DML across multiple objects into fewer statements
Prerequisites: Separating Business Logic from Data Access
The problem it solves
A complex operation (e.g. "create a new customer": an Account, a Contact, and an Opportunity, all related) often ends up doing three separate insert statements scattered across the code, each consuming a DML statement from the transaction's limit and each needing careful sequencing — an Account must exist before a Contact can reference it.
Registering work, then committing once
A Unit of Work exposes methods like registerNew(sObject) and registerRelationship(...) to collect every pending change first, then a single commitWork() call performs the minimum number of DML statements needed, in the correct dependency order, at the very end.
Registering related records before committing
// Conceptual shape — real implementations vary (e.g. fflib's fflib_SObjectUnitOfWork)
UnitOfWork uow = new UnitOfWork();
Account acc = new Account(Name = 'Acme Corp');
uow.registerNew(acc);
Contact con = new Contact(LastName = 'Doe');
uow.registerNew(con);
uow.registerRelationship(con, Contact.AccountId, acc);
uow.commitWork(); // one coordinated set of DML statements, correctly ordered
registerRelationship() tells the Unit of Work that the Contact needs the Account's Id once it exists — so it knows to insert the Account first, then fill in AccountId on the Contact before inserting it.
Exercise
In a comment, explain why registering an Account and a related Contact with a Unit of Work is safer than inserting them separately by hand.
Show hint
Think about ordering and consistency if something in between the two inserts goes wrong.
The Unit of Work Pattern — Quick Check
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A Unit of Work collects all the record changes a complex operation needs to make — across several different objects — and commits them together in one coordinated, minimal set of DML statements, instead of each part of the operation firing its own scattered inserts and updates.