Link objectA with ObjectB : UOW salesforce (Database.upsert)
public class UnitOfWorkExample {
// Custom helper for managing dependencies
public class UpsertUnitOfWorkHelper implements fflib_SObjectUnitOfWork.IDoWork {
private ObjectA__c objARecord;
private ObjectB__c objBRecord;
public UpsertUnitOfWorkHelper(ObjectA__c objARecord, ObjectB__c objBRecord) {
this.objARecord = objARecord;
this.objBRecord = objBRecord;
}
public void doWork() {
// Populate ObjectB's LookupField__c with ObjectA's Id
objBRecord.LookupField__c = objARecord.Id;
}
}
// Method to handle upserting ObjectA and ObjectB with dependency
public static void upsertObjects() {
// Create Unit Of Work
fflib_SObjectUnitOfWork uow = new fflib_SObjectUnitOfWork(
new Schema.SObjectType[] {
ObjectA__c.SObjectType,
ObjectB__c.SObjectType
}
);
// Prepare ObjectA record
ObjectA__c objARecord = new ObjectA__c(Name = 'Test A', CustomField__c = 'Value A');
// Prepare ObjectB record without LookupField__c populated yet
ObjectB__c objBRecord = new ObjectB__c(Name = 'Test B');
// Register ObjectA for insert
uow.registerNew(objARecord);
// Register custom helper to populate ObjectB's lookup after ObjectA's Id is assigned
uow.registerWork(new UpsertUnitOfWorkHelper(objARecord, objBRecord));
// Register ObjectB for insert
uow.registerNew(objBRecord);
try {
// Commit work for both ObjectA and ObjectB in a single transaction
uow.commitWork();
System.debug('All records committed successfully.');
} catch (Exception e) {
// Handle rollback and log error
System.debug('Error during commitWork: ' + e.getMessage());
throw e; // Re-throw to ensure transaction rollback
}
}
}
Link objectA with ObjectB : UOW salesforce (Database.upsert)
Reviewed by dasfrogpractice
on
05:10
Rating:
No comments: