Hibernate transaction management

Transaction:

A transaction is a sequence of operation which works as an atomic unit. A transaction only completes if all the operations completed successfully. A transaction has the Atomicity, Consistency, Isolation and Durability properties (ACID).

Transaction interface:

Transaction interface provides the facility to define the units of work or transactions. A transaction is associated with a session. We have to call beginTransaction()method of Session to start a transaction (Session.beginTransaction()).

Commonly used methods of Transaction interface:

1. begin(): It starts a new transaction.
Syntax:

public void begin() throws HibernateException

2. commit(): It ends the transaction and flush the associated session.
Syntax:

public void commit() throws HibernateException

3. rollback(): It roll back the current transaction.
Syntax:

public void rollback()throws HibernateException

4. setTimeout(int seconds): It set the transaction timeout for any transaction started by a subsequent call to begin() on this instance.
Syntax:

public void setTimeout(int seconds) throws HibernateException

5. isActive(): It checks that is this transaction still active or not.
Syntax:

public boolean isActive()throws HibernateException

6. wasRolledBack(): It checks that is this transaction roll backed successfully or not.
Syntax:

public boolean wasRolledBack()throws HibernateException

7. wasCommitted():It checks that is this transaction committed successfully or not.
Syntax:

public boolean wasCommitted()throws HibernateException

8. registerSynchronization(Synchronization synchronization): It register a user synchronization callback for this transaction.
Syntax:

public boolean registerSynchronization(Synchronization synchronization)throws HibernateException

Example:

Transaction tx = null;
//Get the session object.
Session session = 
        HibernateUtil.getSessionFactory().openSession();
try{
     tx = session.beginTransaction();
     //Perform some operation here
     tx.commit();
}catch (HibernateException e) {
     if(tx!=null){
          tx.rollback();
     }
     e.printStackTrace(); 
}finally {
         session.close(); 
}

 
Next Topic: Hibernate example using xml mapping.
Previous Topic: Hibernate mapping file with example.