D'fflib
HOWLayers

Unit of Work

Step-by-step guide on how to set up and interact with the Unit of Work, maximise the functions and benefits, while being aware of edge cases and D'fflib-specific functionalities.

Characteristics

The Unit of Work is a utility to simplify and centralise all database interactions, including transaction, exception and rollback management. It improves performance and helps avoid exceeding governor limits, while keeping the code clean and readable. Think of it as a shopping cart which is passed along; each layer can add items, but checkout is controlled by the caller, and performed in a bulkified manner.

Responsibilities

The Unit of Work centralises all DML operations into a single transaction boundary:

Separate database interactions from business logic
Bulkify DML operations by bundling and executing one operation per SObject and DML action combination
Manage transactions and rollbacks: automatically generate savepoints and roll back upon failure to keep the database consistent, centralising repetitive code
Simplify registration of related records in a readable and clean manner

Interactions

InteractionLayers
Called by (Initiation and commit)Entrypoints, including the Domain for Triggers and isolated Services (like incoming APIs), and Trigger Handlers with a deviating Context
Usage (Register to provided instance)Domains, Trigger Handlers, Services
CallingNone. The Unit of Work never calls any other layer or service

Typically, a Unit of Work is initiated by an Entrypoint (which owns and controls the transaction), and is passed to other layers to register record modifications to. Like the creation in a Domain constructor, to be passed into every handler phase, or the construction in a Batch or incoming API Service. These Entrypoints are responsible for handling exceptions and properly logging failures.

Rules

  • Always instantiate a Unit of Work with an explicit dfflib_Database.Context, rather than relying on the default INHERIT.
  • Never instantiate or commit a Unit of Work outside of Entrypoints. Other layers should only receive a Unit of Work as a parameter. (Exception for Domains with specific Trigger Handler needs)
  • Avoid creating multiple Unit of Work instances in one transaction. Be critical whether truly needed.
  • When looping records, register within the loop, rather than in bulk after the loop, to avoid an additional loop within the Unit of Work.

Initiation

How to call

There are different method overloads for instantiating a Unit of Work, to meet the possible business needs.

// Default: metadata-driven SObject sequence, default INHERIT Database Context
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance();

// Apply explicit Database Context, metadata-driven SObject sequence
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );

// Apply deviating SObjects, e.g. for non-registered SObjects, or deviating sequence, default Context
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance(
    new List<SObjectType>{ Room__c.SObjectType, RoomReservation__c.SObjectType }
);

// Apply explicit SObject sequence and Database Context
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance(
    new List<SObjectType>{ Room__c.SObjectType, RoomReservation__c.SObjectType },
    dfflib_Database.Context.NONE
);

With an explicit List<SObjectType> only those SObjectTypes are allowed: registering a record of any other type throws an exception.

Metadata registration

When no List of SObjectTypes is provided, newInstance() uses Dfflib_UOW_Config__mdt to determine the SObject DML sequence.

FieldPurpose
DeveloperNameUnique API name of the record, by convention the SObject API name with __c written as _c
MasterLabelLabel of the record, as shown in Setup
SObjectType__cAPI name of the SObject in the sequence
SortOrder__cDML execution order, sequential order for insert/update/undelete and reverse for delete

Order matters to satisfy SObject dependencies. Parents must be inserted before children, and deleted after. RoomReservation__c looks up both Contact and Room__c, so it should have a higher SortOrder__c; otherwise the Contact might not be inserted yet when the reservation is inserted.

SObjectType__cSortOrder__c
Contact10
Room__c20
RoomReservation__c30

Anatomy (how it works)

In essence, the Unit of Work is just a collection of simple maps that track records per operation and SObjectType combination, and orchestrates their persistence in a bulkified and transactional manner.

Keeping registered records and configurations in memory

List<Schema.SObjectType> m_sObjectTypes;
Map<Schema.SObjectType, List<SObject>> m_newListByType;
Map<Schema.SObjectType, List<IRelationship>> m_relationships;
Map<Schema.SObjectType, Database.DMLOptions> m_newDmlOptions = new Map<Schema.SObjectType, Database.DMLOptions>();

Registrations
The single-responsibility of registration methods is to validate input and store the values in the corresponding map.

public void registerNewDmlOptions( Schema.SObjectType sType, Database.DMLOptions options ){
    m_newDmlOptions.put( sType, options );
}
public void registerNew( SObject record, Schema.SObjectField relatedToParentField, SObject relatedToParentRecord ){
    // Record-validations like an insert not having an Id (yet), but update and delete requiring an Id
    validateRecordForDMLAction( record, DMLActions.dNEW );

    // Check whether this SObjectType was already registered, else initialise list in correct sequence
    // Validating whether SObjectType is supported for the requested DML action (no publish for an Account)
    Schema.SObjectType sObjType = record.getSObjectType();
    if( !m_newListByType.containsKey( sObjType ) ){
        implementSObjectType( sObjType, DMLActions.dNEW );
    }
    m_newListByType.get( sObjType ).add( record );

    if( relatedToParentRecord != null && relatedToParentField != null ){
        registerRelationship( record, relatedToParentField, relatedToParentRecord, DMLActions.dNEW );
    }
}

commitWork() and its fixed sequence

Like the registration methods, no rocket science happens in the commitWork(). It simply iterates over the registered records and relationships in a fixed sequence and performs the corresponding DML operations. Below is a simplified representation of this sequence, with D'fflib extensions highlighted.

Simplified representation of commitWork()
// Return when no work is registered
// Reset SaveResults of possible previous commitWork()
// Set Savepoint (skipped in tests)
try{
    // Publish "before" Platform Events

    // Priority inserts
    // Priority updates
    // Priority upserts
    // Priority deletes - in reverse order

    // Immediate inserts
    // Inserts
    // Immediate updates
    // Upserts
    // Updates
    // Immediate deletes - in reverse order
    // Deletes - in reverse order
    // Undeletes
    // Empty Recycle Bin - in reverse order

    // Send Emails and Approval Processes
    // IDoWork

    // Validate all Relationships were resolved, or throw Exception
} catch( Exception e ){
    // Roll back to the Savepoint
    // Rethrow the Exception
} finally{
    // Publish "after success" or "after failure" Platform Events
    // Reset all registered work to avoid accidental duplicate processing
}

While matching methods have the same behaviour in both implementations, the internals differ. In fflib:

  • SObject sequence comes from the Application class, instead of metadata.
  • Maps are initialised for all configured SObjectTypes, not only for registrations.
  • Maps are stored per String instead of SObjectType, requiring casts.
  • Maps are kept even after the work has been committed, instead of reset.
  • Relationships are per SObjectType, instead of per SObjectType-DMLAction combination.
  • Savepoints are always set, and not excluded in unit tests.
  • Advanced steps like resolving email relationships are cast to IDoWork.
  • Several methods and hooks are virtual and can be overridden for extensions.

The base sequence of commitWork() matches D'fflib, without the D'fflib extensions. Note that fflib sends emails after IDoWork, while D'fflib sends them before.

public void commitWork(){
    // Set Savepoint
    try{
        // Publish "before" Platform Events
        // Inserts
        // Upserts
        // Updates
        // Deletes - in reverse order
        // Empty Recycle Bin - in reverse order
        // Resolve Email Relationships
        // IDoWork
        // Email work as last item
    } catch( Exception e ){
        // Roll back to the Savepoint
        // Rethrow the Exception
    } finally{
        // Publish "after success" or "after failure" Platform Events
    }
}


Standard methods

Access control (Context)

The Database Context determines the sharing and permission model applied to all DML during commitWork(). It can be set at construction and possibly overridden with setContext(). The Context is applied at commitWork(), so it covers all work registered before and after calling setContext(). Therefore, it's recommended to set this at construction, for ease of future maintainers.

dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance(); // default INHERIT Database Context
uow.setContext( dfflib_Database.Context.FULL );                 // override the Context after construction

fflib has no setContext(). A deviating sharing and permission model requires an IDML implementation to be passed to the constructor. This can be a project-specific custom IDML implementation, or one of the out-of-the-box SimpleDML or UserModeDML implementations.

// Apply explicit SObject sequence and IDML
fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance(
    new List<SObjectType>{ Room__c.SObjectType, RoomReservation__c.SObjectType },
    new fflib_SObjectUnitOfWork.UserModeDML()
);

D'fflib replaces these constructions with the Database Context: the matching IDML is resolved internally, so no project-specific IDML is needed. UserModeDML → FULL. SimpleDML → INHERIT. While migrating, an existing IDML can still be passed, see Running a legacy fflib IDML.

Standard registrations

Each standard registration method accepts both singular and bulkified input parameters. For new and updated records, an overload is available to directly register a relationship while registering the record.

MethodSObjectList<SObject>Relationship
registerNew (insert)
registerDirty (update)
registerDeleted (delete)
registerEmptyRecycleBin (remove from recycle bin)
registerPermanentlyDeleted (delete and remove from bin)
registerUndeleted (undelete)

For example, cancelling reservations by updating only their status (cancelReservations):

CTRL_RoomReservations.cancelReservations
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
for( Integer i = 0, j = reservationIds.size(); i < j; i++ ){
    uow.registerDirty(
        new RoomReservation__c( Id = reservationIds[ i ], Status__c = DOM_RoomReservations.STATUS_CANCELLED )
    );
}
uow.commitWork();

Update specific fields (dirtyFields)

Sometimes the backend receives a full record with most fields populated, while it's unknown whether those match the database, and only one field should be updated. Either instantiate a new record with only the Id and the changed field (like the example above), or call registerDirty passing a List<SObjectField>.

  • Instead of the passed record, the Unit of Work registers a clean new SObject( Id ) holding only the listed fields.
  • Repeated calls for the same Id enrich the same registered record: field lists are merged, not replaced.
  • No reference to the input record is kept: changes made to it after registration are ignored until registerDirty( record, dirtyFields ) is called again.
  • Calling registerDirty( record ) without fields after a dirtyFields registration of the same record throws an exception, as the Unit of Work can't determine what to update.
  • It is possible to registerDirty by dirtyFields, when the record has no Id set yet. See lifecycle edge cases.
SignaturePurpose
registerDirty( SObject record, List<SObjectField> dirtyFields )Single record
registerDirty( List<SObject> records, List<SObjectField> dirtyFields )Bulk, same fields for every record
registerDirty( SObject record, List<SObjectField> dirtyFields, SObjectField relatedToParentField, SObject relatedToParentRecord ) Single record with relationship
// single record, two fields to update
uow.registerDirty( room, new List<SObjectField>{ Room__c.PricePerNight__c, Room__c.IsActive__c } );
// bulk records, one field to update
uow.registerDirty( rooms, new List<SObjectField>{ Room__c.PricePerNight__c } );
// single record, one field to update, with relationship
uow.registerDirty(
    roomReservation,
    new List<SObjectField>{ RoomReservation__c.Status__c },
    RoomReservation__c.Room__c,
    room
);

Lifecycle

There are a couple of tricks and caveats in the setup of the Unit of Work that help when you know them.

  • Salesforce Id automatically set after insert
  • Local assignments to an already registered record
  • Insert and update record in same Unit of Work
  • Continue using the same Unit of Work

Salesforce Id automatically set after insert

Like in standard Apex, and because of keeping track of references, the Salesforce Id is automatically set on the record after it is inserted. This implies you can continue working with the registered record and also enables the Unit of Work to resolve relationships within one commitWork().

Local assignments to an already registered record

When you make changes to an already registered record, you don't need to registerDirty again, as the reference is tracked. This does not apply to dirtyFields registrations, which register a clean copy. This implies you should be conscious when modifying records in Apex in between registration and committing the Unit of Work.

// Process new reservation and register for insertion
RoomReservation__c roomReservation = new RoomReservation__c( 
    Status__c = DOM_RoomReservations.STATUS_SUBMITTED, ... 
);
uow.registerNew( roomReservation );

// Perform additional logic, like validating Payment status
roomReservation.Status__c = DOM_RoomReservations.STATUS_PAID;

// Save to the database. Due to the reference being tracked, the record will be inserted with 'PAID' status.
uow.commitWork();

Insert and update record in same Unit of Work

It is possible to insert a record and then update it within the same Unit of Work, even with registration via dirtyFields. The Unit of Work generates an internal identifier to match relationships and to ensure the correct sequence of operations. However, for validations to pass it is important to call registerNew before registerDirty.

// Register new room
Room__c room = new Room__c( Name = 'Deluxe Suite', PricePerNight__c = 200 );
uow.registerNew( room );

// Update record to e.g. trigger an external integration;
// Be conscious not to modify the original record, as the change would then already be included in the insert
uow.registerDirty( room );

Continue using the same Unit of Work

To enable reusing the same Unit of Work, commitWork() automatically resets all registrations afterwards, both after success and after failure (resetWork() ). SaveResults are reset at the start of the next commitWork(), as otherwise you wouldn't be able to fetch the results after commitWork() completion. Both can also be called manually: uow.resetWork() and uow.resetSaveResults().

This could be useful when needing isolated transactions, or e.g. to register a Log after completion, based on success or failure.

dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
uow.registerNew( rooms );
uow.commitWork(); // registrations are reset automatically
uow.registerDirty( reservations );
uow.commitWork(); // the rooms are not inserted again
Reset after commitWork()Kept after commitWork()
Registered records, events, emails and approval processesDatabase Context
RelationshipsSObjectTypes provided at construction
DML options and AllOrNoneSaveResults, until the next commitWork()
Registered IDoWork

Reset only happens within commitWork()

The automatic reset runs in the finally of commitWork(). When an exception is thrown before commitWork() is called, those registrations remain. Reusing that Unit of Work, e.g. to insert a log, would also insert the previously registered Contacts. Thus, when reusing a Unit of Work in a finally block, it is important to explicitly reset the work before registering new operations.

SRVi_RoomReservations.handleRequest
try{
    ...
    uow.commitWork();
} catch( ... ){
    ...
} finally{
    // Optionally, log the request for auditing purposes based on the set Response
    // Allowing reuse of the same Unit of Work to e.g. publish a Platform Event
    // Reset explicitly to ensure when an Exception is thrown before commitWork(), the previously registered work is reset as well
    // uow.resetWork();
}

DML options and AllOrNone

To meet the business requirements, you sometimes need to specify DML options or the allOrNone behaviour. Define per SObjectType which options apply.

// DML options for insert and update
registerNewDmlOptions( SObjectType sType, Database.DMLOptions options )
registerDirtyDmlOptions( SObjectType sType, Database.DMLOptions options )

// AllOrNone options for most DML operations
registerNewAllOrNone( SObjectType sType, Boolean allOrNone )
registerDirtyAllOrNone( SObjectType sType, Boolean allOrNone )
registerDeletedAllOrNone( SObjectType sType, Boolean allOrNone )
registerUndeletedAllOrNone( SObjectType sType, Boolean allOrNone )
registerUpsertedAllOrNone( SObjectType sType, Boolean allOrNone )
Database.DMLOptions options = new Database.DMLOptions();
options.duplicateRuleHeader.allowSave = true;
uow.registerNewDmlOptions( RoomReservation__c.SObjectType, options );
uow.registerDirtyDmlOptions( RoomReservation__c.SObjectType, options );

uow.registerNewAllOrNone( RoomReservation__c.SObjectType, false ); // continue past failing records
  • Setting allOrNone = false enables SaveResults automatically, see SaveResults.
  • Immediate operations are not affected by DML options or AllOrNone.
  • Options are reset after commitWork(): register them again when reusing the Unit of Work.

Platform Events

MethodSObjectList<SObject>Publication moment
registerPublishBeforeTransactionFirst, before any DML
registerPublishAfterSuccessTransactionLast, only when all work succeeded
registerPublishAfterFailureTransactionLast, only after a failure and rollback
// Register standard event publication before any DML
uow.registerPublishBeforeTransaction( new BatchApexErrorEvent() );
// Register custom event to publish only when the commit succeeds
uow.registerPublishAfterSuccessTransaction( new AsyncProcess__e() );
// Register custom event to publish only when the commit fails
uow.registerPublishAfterFailureTransaction( new AsyncProcess__e() );
  • fflib supports custom events; D'fflib also allows standard platform events to be published .
  • Registering a record that is not an event throws an exception.
  • After a DML failure, the exception is rethrown. To ensure the event is not rolled back, it's important to configure Publish Immediately on the custom platform event instead of Publish After Commit.

Relationships

Inserting a collection of parents and children in one transaction meant map complexity before fflib. It's impossible to separate concerns as you'll construct the parent and child records in memory, followed by a try-catch statement for the DMLs. But in that try-catch block, you'll also need to assign the parent Id to each child's lookup. Thus, scattered logic, mixing business and operational scope.

The Unit of Work takes this over: register the parent, child and the relationship, even while the parent has no Id yet, and let commitWork() resolve the relationship "just in time". It keeps track of the reference in an internal map and, just before the child's DML, resolves the relationship and assigns the parent's Id.

SRVi_RoomReservations.handleRequest
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
List<Wrapper_Booking> bookings = payload.bookings;

// Query contacts based on email
Map<String, Contact> contactsByEmail = matchGuests( bookings );

// Process each booking and populate output variable
List<RoomReservation__c> reservations = new List<RoomReservation__c>();
for( Integer i = 0, j = bookings.size(); i < j; i++ ){
    Wrapper_Booking booking = bookings[ i ];
    
    // Validate whether Contact exists for guest email, or create new one
    String key = booking?.guest?.email?.toLowerCase();
    Contact c = contactsByEmail.get( key );
    if( c == null ){
        c = booking.guest.convertToContact();
        // Registered in the map, so multiple reservations of the same new guest share one Contact
        contactsByEmail.put( key, c );
        uow.registerNew( c );
    }

    // Create reservation and register for insertion
    // Register relationship between reservation and Contact, regardless of Contact.Id already known, or pending insertion
    RoomReservation__c reservation = booking.reservation.convertToReservation();
    uow.registerNew( reservation, RoomReservation__c.Contact__c, c ); 
    
    reservations.add( reservation );
}

// Commit work to insert Contacts, resolve relations on RoomReservation__c and insert the reservations
uow.commitWork();
List<Wrapper_Booking> bookings = payload.bookings;

// Query contacts based on email
Map<String, Contact> contactsByEmail = matchGuests( bookings );

// Keep track of records to insert, to allow one transaction
List<Contact> contactsToInsert = new List<Contact>();
List<RoomReservation__c> reservationsToInsert = new List<RoomReservation__c>();
// Contact instance per reservation, aligned by index; a new Contact has no Id yet, but receives it on insert,
// so the lookup is resolved from the same instance afterwards
List<Contact> contactPerReservation = new List<Contact>();
for( Integer i = 0, j = bookings.size(); i < j; i++ ){
    Wrapper_Booking booking = bookings[ i ];
    String key = booking?.guest?.email?.toLowerCase();
    Contact c = contactsByEmail.get( key );
    if( c == null ){
        c = booking.guest.convertToContact();
        // Registered in the map, so multiple reservations of the same new guest share one Contact
        contactsByEmail.put( key, c );
        contactsToInsert.add( c );
    }
    contactPerReservation.add( c );
    reservationsToInsert.add( booking.reservation.convertToReservation() );
}

// Manage the transaction manually, so a failing reservation insert does not leave orphan Contacts
Savepoint sp = Database.setSavepoint();
try{
    // Insert the Contacts first, as their Ids are required for the reservation lookup
    Database.insert( contactsToInsert, true, AccessLevel.SYSTEM_MODE );

    // Resolve the lookup from the aligned Contact instance, now holding an Id for both existing and new guests
    for( Integer i = 0, j = reservationsToInsert.size(); i < j; i++ ){
        reservationsToInsert[ i ].Contact__c = contactPerReservation[ i ]?.Id;
    }
    Database.insert( reservationsToInsert, true, AccessLevel.SYSTEM_MODE );
} catch( Exception ex ){
    if( sp != null ){
        Database.rollback( sp );
    }
    // Rethrow, so the original exception type is mapped to a response below
    throw ex;
}

As you can see, there's no need for maps and other logic to keep the records referenced and recognised. Especially when the parents don't have Ids yet, this can be rather cumbersome. With the above structure, it doesn't matter whether the parent (Contact) already existed or was pending insertion (new guest): the highlighted registration is identical for both.

Relationships are typically registered inline (see Standard registrations), or with registerRelationship:

SignaturePurpose
registerRelationship( SObject record, SObjectField relatedToField, SObject relatedTo )Resolve the lookup to a parent record, registered in the same Unit of Work or already existing
registerRelationship( SObject record, SObjectField relatedToField, SObject relatedTo, DMLActions specificDMLAction ) Same, restricted to one DML action
registerRelationship( SObject record, SObjectField relatedToField, SObjectField externalIdField, Object externalId )Resolve the lookup by an external Id value, without a parent record
registerRelationship( SObject record, SObjectField relatedToField, SObjectField externalIdField, Object externalId, DMLActions specificDMLAction ) Same, restricted to one DML action
registerRelationship( Messaging.SingleEmailMessage email, SObject relatedTo )Populate the email WhatId, equal to registerEmail( email, relatedTo )
registerRelationship( Approval.ProcessRequest process, SObject relatedTo ) Populate the ObjectId (submit request) or WorkitemId (workitem request), equal to registerApprovalProcess( process, relatedTo )
// Register multiple relationships to the same record
uow.registerNew( reservation, RoomReservation__c.Contact__c, c );
uow.registerRelationship( reservation, RoomReservation__c.Room__c, room );

// Restrict the relationship to a specific DML action
uow.registerRelationship( reservation, RoomReservation__c.Room__c, room,
    dfflib_SObjectUnitOfWork.DMLActions.dNEW ); // 'd' prefix, as NEW and INSERT are reserved words

// Resolve the lookup by an external Id value instead of a record
uow.registerRelationship( reservation, RoomReservation__c.Contact__c, Contact.External_Id__c, 'abc123' );
  • registerDirty with relationship accepts a record without Id when it is registered for insert in the same Unit of Work, supporting 1:1 constructions like a parent lookup to a child inserted in the same transaction .
  • A relationship is resolved once, at the first DML action that processes the record (upserts included). Pass a DMLActions value (dNEW, dUPDATE, dUPSERT, dDELETE) to bind it to a specific action, e.g. when the record is registered for multiple actions .
  • An unresolved relationship (e.g. the child was never registered for DML) throws an exception at the end of commitWork() .

Advanced methods

Approval Process

SignaturePurpose
registerApprovalProcess( Approval.ProcessRequest approvalProcess )Submit, approve or reject an approval process
registerApprovalProcess( Approval.ProcessRequest process, SObject relatedTo )Same, populating the ObjectId (submit request) or WorkitemId (workitem request) from the related record

Approval processes are processed after all DML, so the related record may be inserted by the same Unit of Work.

Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
request.setComments( 'Group reservation exceeds the room capacity' );

uow.registerNew( reservation );
uow.registerApprovalProcess( request, reservation ); // ObjectId populated after the insert
uow.commitWork();

Email

SignaturePurpose
registerEmail( Messaging.Email email )Send any email after all DML
registerEmail( Messaging.SingleEmailMessage email, SObject relatedTo ) Same, populating the WhatId from the related record, as only a SingleEmailMessage supports a WhatId
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTargetObjectId( contactId );
email.setTemplateId( confirmationTemplateId );

uow.registerNew( reservation );
uow.registerEmail( email, reservation ); // WhatId populated after the insert
uow.commitWork();

Emails are sent within the transaction: a failing send rolls back all registered DML.

IDoWork

IDoWork is an interface that can be used to implement any database operation which is not supported yet. registerWork() registers custom work executed during commitWork(), like converting leads, for which no register method exists: the conversion then shares the transaction, savepoint and rollback of the Unit of Work.

SignaturePurpose
registerWork( dfflib_SObjectUnitOfWork.IDoWork work )Execute work.doWork() as last operation in commitWork()
public with sharing class LeadConvertWork implements dfflib_SObjectUnitOfWork.IDoWork{
    private final List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();

    public void register( Database.LeadConvert leadConvert ){
        leadConverts.add( leadConvert );
    }

    public void doWork(){
        Database.convertLead( leadConverts ); // one bulkified call for all registered conversions
    }
}

// Register the work once, and add the conversions within the loop
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>(); // ... populated by your business logic
LeadConvertWork leadConvertWork = new LeadConvertWork();
uow.registerWork( leadConvertWork );
for( Integer i = 0, j = leadConverts.size(); i < j; i++ ){
    leadConvertWork.register( leadConverts[ i ] );
}
uow.commitWork();
  • doWork() runs as you define it. Database Context does not apply to it.
  • An exception thrown in doWork() rolls back all registered DML.

Immediate

Immediate operations call Database.insertImmediate(), updateImmediate() and deleteImmediate(), used for external objects, big objects or special objects (like ThirdPartyAccountLink).

MethodSObjectList<SObject>Relationship
registerNewImmediate
registerDirtyImmediate
registerDeletedImmediate
uow.registerNewImmediate( externalRecord );
uow.registerDirtyImmediate( externalRecord );
uow.registerDeletedImmediate( externalRecord );
  • Each immediate operation executes before its standard counterpart, see the commitWork() sequence.
  • Immediate operations on external objects are not part of the Salesforce transaction: a rollback does not revert them.
  • DML options and AllOrNone do not apply to immediate operations.

Priority

The fixed sequence of the Unit of Work might sometimes mismatch the business requirement, like when a reservation should be postponed by one day, but updating is not allowed. Then the original reservation should be cancelled before the rescheduled reservation can be inserted, to avoid triggering the overlap validation.

Priority operations execute before all standard operations, allowing a deviation from the fixed DML sequence within one Unit of Work. As you can see in the sequence, priority operations have their own fixed sequence (inserts, updates, upserts, deletes) and are performed sooner, giving a second dimension of control. In fflib, this required multiple Unit of Work instances and commits.

MethodSObjectList<SObject>Relationship
registerPriorityNew
registerPriorityDirty
registerPriorityUpsert
registerPriorityDeleted
// Cancel the old booking first (with priority), to free up the room, before inserting the new booking
uow.registerPriorityDirty( new RoomReservation__c( Id = oldId, Status__c = DOM_RoomReservations.STATUS_CANCELLED ) );
uow.registerNew( new RoomReservation__c( Room__c = roomId, ... ) );
uow.commitWork();

With registerDirty, the insert would execute first and fail on the occupied room.

SaveResults

SaveResults are disabled by default, as storing them consumes memory and CPU while they are rarely needed. When partial success should be possible, SaveResults are necessary to determine which records succeeded and which failed.

Setting allOrNone = false via any register*AllOrNone method automatically enables SaveResult storage. When allOrNone is disabled via register*DmlOptions, call uow.setSaveResultsRequired( true ) explicitly.

CTRL_RoomReservations.createReservations
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
uow.registerNewAllOrNone( RoomReservation__c.SObjectType, false );
uow.registerNew( reservations );
uow.commitWork();

// Loop SaveResults to collect any errors for partial success feedback
List<Database.SaveResult> saveResults = uow.getNewResults( RoomReservation__c.SObjectType );
Map<Integer, String> errors = new Map<Integer, String>();
for( Integer i = 0, j = saveResults?.size() ?? 0; i < j; i++ ){
    Database.SaveResult sr = saveResults[ i ];
    if( !sr.isSuccess() ){
        errors.put( i, sr.getErrors()[ 0 ].getMessage() );
    }
}

SaveResult getters are defined to return null when no DML ran for that SObjectType or SaveResults were disabled. Hence, null-safe saveResults?.size() ?? 0.

GetterReturns
getNewResults( SObjectType )List<Database.SaveResult> for inserts
getDirtyResults( SObjectType )List<Database.SaveResult> for updates
getUpsertResults( SObjectType )List<Database.UpsertResult> for upserts by external Id
getDeletedResults( SObjectType )List<Database.DeleteResult>
getUndeletedResults( SObjectType )List<Database.UndeleteResult>
getEmptyRecycleBinResults( SObjectType )List<Database.EmptyRecycleBinResult>
getPublishResults( SObjectType )List<Database.SaveResult> for published events
getEmailResults()List<Messaging.SendEmailResult>
getApprovalProcessResults()List<Approval.ProcessResult>

SaveResults are kept after commitWork(), and reset automatically at the start of the next commitWork(). uow.resetSaveResults() clears them manually.

Currently, the enablement of SaveResults is for all SObjectTypes. It is on our backlog to narrow this to the specific SObjectType. This would further improve performance for larger transactions.

Upsert

Both fflib and D'fflib have two upsert variants:

  1. Simply dispatching to registerNew() if the record has no Id, or registerDirty() when an Id is set
  2. Performing a genuine Database.upsert() matching on an external Id field

The upsert-specific configurations (AllOrNone and SaveResults) apply only to the externalIdField variant.

SignatureBehaviour
registerUpsert( SObject record )Dispatches to registerNew() (no Id) or registerDirty() (Id set)
registerUpsert( List<SObject> records )Same, bulk
registerUpsert( SObject record, SObjectField externalIdField )Genuine Database.upsert() matching on an external Id field
registerUpsert( List<SObject> records, SObjectField externalIdField )Same, bulk
registerUpsert( SObject record, SObjectField externalIdField, SObjectField relatedToParentField, SObject relatedToParentRecord )Same as single, registering the relationship to the parent inline

For the Database.upsert() variant:

  • The field must be an external Id field, or Id, on the same SObjectType as the registered record.
  • The field should be populated for all registered records.
  • Multiple external Id fields may be registered for the same SObjectType in one Unit of Work . fflib supports one external Id field per SObjectType.

Testing a Unit of Work

See Testing & Mocking for the full testing patterns.

The calling class is tested with a mocked Unit of Work: no DML happens, and you verify what was registered and committed. Examples below come from CTRL_RoomReservationsTest and SRVi_RoomReservationsTest.

Define the mock

fflib_ApexMocks mocks = new fflib_ApexMocks();
dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks );

Verify registrations and commit

// Standard, simple verifications whether the Unit of Work was called
( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( reservations );
( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).commitWork();

// Verify the record by its relevant field values, and the relationship to the (new) Contact
( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew(
    fflib_Match.sObjectWith( new Map<SObjectField, Object>{
        RoomReservation__c.Room__c          => ROOM_ID,
        RoomReservation__c.CheckInDate__c   => CHECK_IN,
        RoomReservation__c.CheckOutDate__c  => CHECK_OUT,
        RoomReservation__c.Status__c        => DOM_RoomReservations.STATUS_SUBMITTED
    } ),
    ( Schema.SObjectField ) fflib_Match.eq( RoomReservation__c.Contact__c ),
    fflib_Match.sObjectWith( expectedContactMap )
);

// Verification can also be done with ArgumentCaptor
fflib_ArgumentCaptor argumentCaptor = new fflib_ArgumentCaptor();
( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( argumentCaptor.capture() );
List<RoomReservation__c> registeredRecords = ( List<RoomReservation__c> ) argumentCaptor.getValues();
// ...
  • Once a matcher is used, every argument needs one: hence fflib_Match.eq() for the relationship field.
  • A mocked commitWork() inserts nothing, so registered records keep a null Id. Be aware fflib_Match.anyObject() does not match null, thus use fflib_Match.isNull() as backup like in stubResponseService of SRVi_RoomReservationsTest.

Simulate a DML failure

To simulate a DML failure during commit, use doThrowWhen, as commitWork() is a void method and cannot return a value.

// Given - set data
String exceptionMessage = 'Matching rule fired';

// set mocks
mocks.startStubbing();
( ( dfflib_ISObjectUnitOfWork ) mocks.doThrowWhen( new DmlException( exceptionMessage ), uowMock ) ).commitWork();
mocks.stopStubbing();

Stub SaveResults for partial success

// The first record succeeds, the second fails
List<Database.SaveResult> saveResults = new List<Database.SaveResult>{
    dfflib_UT_Utils.createSaveResult( fflib_IDGenerator.generate( RoomReservation__c.SObjectType ), true, null ),
    dfflib_UT_Utils.createSaveResult( null, false, dmlMessage )
};

mocks.startStubbing();
mocks.when( uowMock.getNewResults( RoomReservation__c.SObjectType ) ).thenReturn( saveResults );
mocks.stopStubbing();

Mock SaveResults according to the documentation.
The recordId, for saveResult.getId(), is only populated upon successful operations.


Migration steps

For existing code to leverage D'fflib features, a few migration steps are required. The steps below apply once D'fflib extensions are installed (Getting Started).

Caller changes

  1. Ensure Dfflib_UOW_Config__mdt records exist with the correct sequence
  2. Change [Application].unitOfWork.newInstance() to dfflib.unitOfWork.newInstance()
  3. Pass a Database Context to the Unit of Work to enforce the desired sharing and FLS behaviour

Test class changes

  1. Replace Unit of Work stubs with dfflib.unitOfWork.defineMock( mocks ), see Testing a Unit of Work and the Testing & Mocking article

Backward compatibility

Two constructs have been replaced, since better approaches have been implemented:

  1. Custom IDML implementations should eventually be replaceable by features like Context and SaveResults. D'fflib supports running existing IDML implementations for backward compatibility. Though this should be used with caution as detailed in "Running a legacy fflib IDML".
  2. Overridable virtual hooks within the Unit of Work have been removed, as they consumed performance while not adding benefit in the current construct.

Carefully review existing IDML implementations and hook overrides and migrate their logic to use the new mechanisms provided by D'fflib. If you can't find a fitting migration, we'd be happy to think along.

D'fflib supports running existing IDML implementations, to ease migration and backward compatibility. The internal LegacyDMLAdapter converts the IDML implementation to make it compatible with D'fflib's Unit of Work. No changes are required to the legacy IDML implementations as original fflib_SObjectUnitOfWork.IDML, SimpleDML etc remain available.

To keep using an existing IDML while migrating, simply:

  1. Call dfflib.unitOfWork.newInstance( List<SObjectType>, IDML ).
  2. Call dfflib.unitOfWork.newInstance( IDML ) and ensure Dfflib_UOW_Config__mdt records exist.

References to SimpleDML and UserModeDML are recommended to be migrated directly.

IDMLContext
SimpleDMLINHERIT
UserModeDMLFULL
fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new fflib_SObjectUnitOfWork.SimpleDML() );
fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new fflib_SObjectUnitOfWork.UserModeDML() );
fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new ProjectSpecificDML() );
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.INHERIT );
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( new ProjectSpecificDML() );

Only for backward compatibility while migrating

For performance reasons, no safeguards are built in on 'non-IDML-supported methods'. Don't update or extend the Unit of Work, and don't combine a legacy IDML with new D'fflib methods. To use new functionality, replace the IDML with its D'fflib successor, dfflib_Database.Context.

  • Works: registerNew, registerDirty, registerUpsert (the IDML must implement IDMLUpsertable), registerDeleted, registerPermanentlyDeleted, the three registerPublish* methods, relationships, emails and approval processes. Emails and approvals are sent through the default INHERIT proxy, never through the IDML.
  • Exceptions in commitWork(), rolling back the transaction: priority, immediate and undelete registrations , and registerUpsert with an IDML that doesn't implement IDMLUpsertable (System.TypeException).
  • Silently ignored: register*DmlOptions and register*AllOrNone. setSaveResultsRequired( true ) returns no SaveResults (they stay null).
  • setContext() replaces the legacy IDML with the Context proxy.
  • Call-counts might differ from fflib as D'fflib only calls IDML when work is registered.

Except for the listed items, the content on this site is licensed under CC-BY-NC-4.0
and allows sharing, provided an appropriate credit and link to source.

On this page