Friday, July 17, 2015

What is Hibernate Transaction?

Transactions : -  Hibernate Transactions is number operations which you are performing on your database i.e. insert, update, delete etc. Hibernate Transaction is a Unit-Of-Work or in the simple words we can say its a single circuite board if one circuit fails whole database operation will get roll backed.

Hibernate Transactions is an Interface which following the Database ACID (Atomicity, Consistency, Isolation and Durability) property and it uses the JDBC connections and JTA resources without any locking behaviour on the  database.

Hibernate Transaction comprises of the following methods : -

  1. void begin() : – It is used to starts a new transaction.
  2. void commit() : – It is used to ends the unit of work unless we are in FlushMode.NEVER.
  3. void rollback() : – Used for focefully rollback the transaction.
  4. void setTimeout(int seconds) : -  It sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
  5. boolean isAlive() : -  Checks if the transaction is still alive.
  6. void registerSynchronization(Synchronization s) : -  Registers a user synchronization callback for this transaction.
  7. boolean wasCommited() : -  Checks if the transaction is commited successfully.
  8. boolean wasRolledBack() : -  Checks if the transaction is rolledback successfully.

So how do we use transaction in out code. Please find the below code blocks : -

 

try{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 
         //begin the transaction
        Transaction trans=session.beginTransaction();
          
        //Save the person in database
        session.saveOrUpdate(personObj);
          
        //Commit the transaction
        trans.commit();
}catch (Exception ex) {  
 ex.printStackTrace();  
 tx.rollback();  
}  
finally {
 session.close();
}

No comments:

Post a Comment