Implementation
Introduction
The Persistence Manager allows to manage the persistence of any SObject Hyerarchy in Salesforce.
It’s important to note that the Persistence Manager receives a Map<String, Object> hierarchy representing the different SObject records and relationships, as there is no way to build a SObject hierarchy in Apex with all the relationships to be persisted, only those relationships that can be returned by a SOQL query.
In order to build this Map you can do it in different ways:
- Programatically Building the Map
- Loading an Object Tree definition.
- Applying a Data Map to the desired SObject / Map.
Persisting
The Persistence Manager is not only in charge of inserting/updating/deleting records into the database but also from resolving automatically the relationships between the different records. This way the developer does not need to handle the relationship population manually reducing the complexity of the code and the risk of errors.
There are two different ways to persist records:
One Shot
Objects can be persisted directly by calling the PersistenceManager.persist(Map<String, Object>) method, or passing a List
These methods will return the persisted SObject/s.
Persistence Queue
The Persistence Manager also offers the possibility to persist records in a Queue, and then execute the queue in a single transaction. This is useful when you need to persist records in different moments of the execution, and then execute all the DML operations in a single transaction. This combined with the Unit of Work functionality allows to manage the transactional logic in a very simple and performant way.
To enqueue records you can use the PersistenceManager.enqueuePersist(Map<String, Object>) method, or passing a List
Once you want to execute the queue you can call the PersistenceManager.commitQueue()
Special Cases
Deleting
You can also delete records with the Persistence Manager by setting a Key with the name ‘DELETE’ at the record level you want to delete.
It’s not recommended to delete records automatically. Please make sure you know what you are doing before using this functionality.
Rootable Option
The Persistence Manager offers the option to define a Rootable object. This is useful when you want to persist a SObject hierarchy that has a root object that must be populated along the hierarchy. For instance, when you want to persist an Asset Hierarchy and set the Root Asset relationship / lookup in all the levels.
For this, you can pass the Options object to the persist method which has two members:
- rootableObject: The root SObject Type that must be populated in all the hierarchy.
- rootableField: The field name of the root SObject that must be populated in all the hierarchy (if the field exists).
Once the Engine find the first level of the hierarchy with the SObject Type specified in the rootableObject it will use that level record Id to populate the rootableField in all the hierarchy.