Rolling back DML operation in Apex method

What is the best way to rollback some changes to the database inside an Apex method?

For example, in an Apex method, I insert multiple records (Opportunity / Quote / QuoteLineItems). When I execute my method, I want every DML operation to be executed without any errors. If any error is detected, I want the changes to be rollback (if the error happen between Quote and QuoteLineItem insertion, I want to remove the Opportunity AND Quote).

Is Savepoint sp = Database.setSavepoint(); the best alternative, or is there something I’m missing?

Thanks!

Answer

A Savepoint is exactly what you want. This is all apart of Transactions in Salesforce. You will want something like:

Savepoint sp = Database.setSavepoint();
try{
    // DML statements here
    insert opps;
    insert quotes;
    insert quoteItems;
}catch(Exception e){
    // An exception was caught. We need to revert back to our Savepoint
    // This will rollback all successful changes. So, if opps saved successfully
    // and then quotes failed, the opps will be rolled back as well
    Database.rollback(sp);

    // Add the error to the page for the user to see
    ApexPages.addMessages(e);
}

Attribution
Source : Link , Question Author : jpmonette , Answer Author : Jesse Altman

Leave a Comment