Database.setSavepoint() in Salesforce apex can be used to rollback the transaction to a point. It helps in partial rollback on the transactions.
Database.setSavepoint() is used to define a point at which DML operations can be rolled back. If any error occurs during DML Operations, that contains many statements, the application will be rolled back to the most recent save point and the entire transaction will not be aborted.
Sample Code without Database.setSavepoint:
try {
Account objAcc = new Account(
Name = 'Testing Account'
);
insert objAcc;
Contact objContact = new Contact(
FirstName = 'Test'
);
insert objContact;
} catch( DMLException e ) {
System.debug(
'Exception is ' +
e.getMessage()
);
}
In the above code, if the Contact creation fails, it won’t rollback the Account insertion. Account record creation will be committed to the Database.
Sample Code with Database.setSavepoint:
Savepoint objSavePoint = Database.setSavepoint();
try {
Account objAcc = new Account(
Name = 'Testing Account'
);
insert objAcc;
Contact objContact = new Contact(
FirstName = 'Test'
);
insert objContact;
} catch( DMLException e ) {
System.debug(
'Exception is ' +
e.getMessage()
);
Database.RollBack( objSavePoint );
}
In the above code, if the Contact creation fails, it will rollback the Account insertion. Account record creation will not be committed to the Database.
Note the following:
1. If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
2. References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
3. Each savepoint you set counts against the governor limit for DML statements.