SavePoint and Rollback will help us to maintain transaction for DML statement.
Suppose you have written multiple lines of DML statements in a try block, If any error occurs during DML Operations, the operation will be rolled back to the most recent save point and the entire transaction will not be aborted.
Savepoint sp;
try{
sp = Database.setSavepoint();
Account a = new Account();
a.Name = 'Test Account';
insert a;
Contact c = new Contact(Account = a.Id);
c.FirstName = 'Biswajeet';
c.LastName = 'Samal';
insert c;
}
catch(Exception e){
Database.RollBack(sp);
}
In this example, if any error occurs while inserting the Account ‘a’ or Contact ‘c’, then the entire transaction will be rolled back to SavePoint ‘sp’, as specified in the catch section by Database.Rollback method.
public class PrintSample {
public List<account> objList {get; set;}
public PrintSample() {
objList = new List<account>();
objList = [SELECT Name, Phone FROM Account];
}
}