Skip to content
This repository was archived by the owner on Mar 25, 2020. It is now read-only.

Transaction

Ricky Tobing edited this page Aug 14, 2013 · 2 revisions

To create a transaction use the Transaction object by doing the following:

IDatabase db = ...
Transaction transaction = db.begin(new Batch(){
   public void exec(IDatabase db){
      // do SQL intensive processing here
      ...
   }
});

Transaction will provide common patterns such as Transaction.commit(), Transaction.rollback() and Transaction.end() methods. Best practice is to use the following code snippet everytime.

IDatabase db = ...
Transaction transaction = db.begin(new Batch(){
   public void exec(IDatabase db){
      // do SQL intensive processing here
      ...
   }
});

try{
   // try to commit the batch
   transaction.commit();
}
catch (Exception e){
   // rollback if any error occured
   transaction.rollback();
}
finally{
   // always call end() inside the finally block
   transaction.end();
}

#Transaction.execute() The API provides Transaction.execute() (returns boolean) to avoid the try-catch. The Transaction.execute() method will return a boolean. true if commit is a success, false if commit is a failure and Transaction.rollback() was performed.

boolean success = db.begin(new Batch(){
   public void exec(IDatabase db){
      // do SQL intensive processing here
      ...
   }
}).execute();

The drawback of using this method is that you will never know what exception is thrown.

Clone this wiki locally