Hibernate transaction management


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 rollback() 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.
Synatx: public boolean wasRolledBack()throws HibernateException
7. wasCommitted():It checks that is this transaction committed successfully or not.
Synatx: 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


Transaction tx = null;
//Get the session object.
Session session =
tx = session.beginTransaction();
//Perform some operation here
}catch (HibernateException e) {
}finally {

No comments: