function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dai tran 6dai tran 6 

How can rollback database in apex?

I process insert to some tables:
public PageReference  checkoutPaypal()
    {
      try
      {
          List<AccountUser__c>  listacc =  [SELECT id,AccountId__c FROM AccountUser__c  WHERE  email__c=:email  LIMIT 1];
          AccountUser__c a=new AccountUser__c();
          Account acc=new Account();
          if(listacc.size()>0)
          {
              a=listacc.get(0);             
          }
          else
          {
              acc.Name=name;             
              insert acc;
              //save value ok    
             
              //           
              a.Name=name;
              a.AccountId__c=acc.Id;
              a.Email__c=email;
              a.Status__c=0;
              a.Password__c='0';
              insert a;            
           }
          
            
          Contact con=new Contact();
          con.LastName=name;
          con.Email=email;
          //con.Phone__c=phonenumber;
          con.AccountId=a.AccountId__c;
          insert con;
         
          //
          Contract hd=new Contract();
          hd.AccountId=a.AccountId__c;
          hd.StartDate=system.today();
          hd.ContractTerm=1;
          insert hd;
          
          Order od=new Order();
          od.AccountId=a.AccountId__c;
          od.ContractId=hd.Id; 
          od.EffectiveDate=system.today();
          insert od;
          Double itotalMoney=0;
          if(ids !='')
          {
            
              string searchquery='select ProductCode,Name,ImageName__c,(Select UnitPrice,Pricebook2.Name From PricebookEntries where IsActive=True  Order By UnitPrice ASC )  from Product2 where ProductCode in ('+SOQL_IDs+')'; 
              List<Product2>  MyProducts= Database.query(searchquery); 
              List<OrderItem> lsDetail=new List<OrderItem>();
              for(Integer i=0;i<MyProducts.size();i++)   
              {   
                  String code=MyProducts.get(i).ProductCode;
                  String sl=listCarts.get(code);
                  OrderItem ode=new OrderItem();
                  ode.OrderId=od.Id;
                  ode.Quantity=Double.valueOf(sl);
                  ode.UnitPrice=MyProducts.get(i).PricebookEntries.get(0).UnitPrice;
                  ode.Product2Id=MyProducts.get(i).Id;
                  lsDetail.Add(ode);
                  itotalMoney=itotalMoney+ ode.Quantity * ode.UnitPrice;
              }
              
               insert lsDetail;
          }
         
        
         Pagereference redirectedPage = New PageReference('/apex/payment?amount='+itotalMoney);  
         return redirectedPage;
      }
      catch(DmlException e)
      {
          err=e.getMessage();
      }
      
       return null;
      
    }
Current if function occur error, some process still insert data ok.
I want rollback all, if occur error/
How can rollback database in apex?
Best Answer chosen by dai tran 6
PawanKumarPawanKumar
Please try below code. You can see the difference as bold highlighted.

public PageReference  checkoutPaypal()
    {
      // roll back point    
      Savepoint sp = Database.setSavepoint();

      
      try
      {
          List<AccountUser__c>  listacc =  [SELECT id,AccountId__c FROM AccountUser__c  WHERE  email__c=:email  LIMIT 1];
          AccountUser__c a=new AccountUser__c();
          Account acc=new Account();
          if(listacc.size()>0)
          {
              a=listacc.get(0);             
          }
          else
          {
              acc.Name=name;             
              insert acc;
              //save value ok    
             
              //           
              a.Name=name;
              a.AccountId__c=acc.Id;
              a.Email__c=email;
              a.Status__c=0;
              a.Password__c='0';
              insert a;            
           }
          
            
          Contact con=new Contact();
          con.LastName=name;
          con.Email=email;
          //con.Phone__c=phonenumber;
          con.AccountId=a.AccountId__c;
          insert con;
         
          //
          Contract hd=new Contract();
          hd.AccountId=a.AccountId__c;
          hd.StartDate=system.today();
          hd.ContractTerm=1;
          insert hd;
          
          Order od=new Order();
          od.AccountId=a.AccountId__c;
          od.ContractId=hd.Id; 
          od.EffectiveDate=system.today();
          insert od;
          Double itotalMoney=0;
          if(ids !='')
          {
            
              string searchquery='select ProductCode,Name,ImageName__c,(Select UnitPrice,Pricebook2.Name From PricebookEntries where IsActive=True  Order By UnitPrice ASC )  from Product2 where ProductCode in ('+SOQL_IDs+')'; 
              List<Product2>  MyProducts= Database.query(searchquery); 
              List<OrderItem> lsDetail=new List<OrderItem>();
              for(Integer i=0;i<MyProducts.size();i++)   
              {   
                  String code=MyProducts.get(i).ProductCode;
                  String sl=listCarts.get(code);
                  OrderItem ode=new OrderItem();
                  ode.OrderId=od.Id;
                  ode.Quantity=Double.valueOf(sl);
                  ode.UnitPrice=MyProducts.get(i).PricebookEntries.get(0).UnitPrice;
                  ode.Product2Id=MyProducts.get(i).Id;
                  lsDetail.Add(ode);
                  itotalMoney=itotalMoney+ ode.Quantity * ode.UnitPrice;
              }
              
               insert lsDetail;
          }
         
        
         Pagereference redirectedPage = New PageReference('/apex/payment?amount='+itotalMoney);  
         return redirectedPage;
      }
      catch(DmlException e)
      {
          err=e.getMessage();
          
          // rollback entire transaction
          Database.RollBack(sp);

      }
      
       return null;
      
    }

Please mark it best if it helps you. Thanks.

All Answers

PawanKumarPawanKumar
Please try below code. You can see the difference as bold highlighted.

public PageReference  checkoutPaypal()
    {
      // roll back point    
      Savepoint sp = Database.setSavepoint();

      
      try
      {
          List<AccountUser__c>  listacc =  [SELECT id,AccountId__c FROM AccountUser__c  WHERE  email__c=:email  LIMIT 1];
          AccountUser__c a=new AccountUser__c();
          Account acc=new Account();
          if(listacc.size()>0)
          {
              a=listacc.get(0);             
          }
          else
          {
              acc.Name=name;             
              insert acc;
              //save value ok    
             
              //           
              a.Name=name;
              a.AccountId__c=acc.Id;
              a.Email__c=email;
              a.Status__c=0;
              a.Password__c='0';
              insert a;            
           }
          
            
          Contact con=new Contact();
          con.LastName=name;
          con.Email=email;
          //con.Phone__c=phonenumber;
          con.AccountId=a.AccountId__c;
          insert con;
         
          //
          Contract hd=new Contract();
          hd.AccountId=a.AccountId__c;
          hd.StartDate=system.today();
          hd.ContractTerm=1;
          insert hd;
          
          Order od=new Order();
          od.AccountId=a.AccountId__c;
          od.ContractId=hd.Id; 
          od.EffectiveDate=system.today();
          insert od;
          Double itotalMoney=0;
          if(ids !='')
          {
            
              string searchquery='select ProductCode,Name,ImageName__c,(Select UnitPrice,Pricebook2.Name From PricebookEntries where IsActive=True  Order By UnitPrice ASC )  from Product2 where ProductCode in ('+SOQL_IDs+')'; 
              List<Product2>  MyProducts= Database.query(searchquery); 
              List<OrderItem> lsDetail=new List<OrderItem>();
              for(Integer i=0;i<MyProducts.size();i++)   
              {   
                  String code=MyProducts.get(i).ProductCode;
                  String sl=listCarts.get(code);
                  OrderItem ode=new OrderItem();
                  ode.OrderId=od.Id;
                  ode.Quantity=Double.valueOf(sl);
                  ode.UnitPrice=MyProducts.get(i).PricebookEntries.get(0).UnitPrice;
                  ode.Product2Id=MyProducts.get(i).Id;
                  lsDetail.Add(ode);
                  itotalMoney=itotalMoney+ ode.Quantity * ode.UnitPrice;
              }
              
               insert lsDetail;
          }
         
        
         Pagereference redirectedPage = New PageReference('/apex/payment?amount='+itotalMoney);  
         return redirectedPage;
      }
      catch(DmlException e)
      {
          err=e.getMessage();
          
          // rollback entire transaction
          Database.RollBack(sp);

      }
      
       return null;
      
    }

Please mark it best if it helps you. Thanks.
This was selected as the best answer
mritzimritzi
In your code
insert this at before line #3
Savepoint svPoint = Database.setSavepoint();
insert this at after line #76
Database.RollBack(svPoint);
After this line you can optionally add System.debug statement with appropriate message for easily logging the issue.

Doing this will ensure that your database will return to the state it was when the code execution started, if any error happened during processing.

Please mark this as BEST ANSWER, if this helps solve your problem