Salesforce Transaction control is means of enforcing the above concept to your apex code which executes on Salesforce servers.In Salesforce you can do this with two simple methods.
- Savepoint sp = Database.setSavepoint(); - marks the beginning of your transaction and also the point to database should revert in case the operation fails.
- Database.rollback(sp); - undo any changes you have done to the database after the passed save point. This methods takes a save point as a parameter and roll back all the database changes done after the passed save point.
// variable initialization
// your custom validation logic
Savepoint sp = Database.setSavepoint(); // should be before any dml statements that you intend to be undone if the operation fails
try
{
// your dml statements and other logic
}
catch(Exception e )
{
//oops something bad happen before opertion completed
Database.rollback(sp); //undo any dml change done after setting the save point.
}
you can find more about Salesforce Transaction Control Here
One important point to note is Id values of Sobject records save after save point are not cleared on rollback.Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database and, thus, cannot be updated.So it is important you reinitialize your sobjects after rollback else it will generate DML exceptions on subsequent operations such as
- Record ID: cannot specify Id in an insert call
- Record does not exist
No comments:
Post a Comment