Introduction
In this blog, we will learn about the transaction and hibernate transaction management with examples. A transaction is a unit of work. If one step fails in this case, the entire transaction fails (which is termed atomicity). ACID properties (Atomicity, Consistency, Isolation, and Durability) can be used to describe a transaction.

Hibernate Transaction Management
Transaction interface
The transaction interface allows you to define work units or transactions. A transaction is linked to a session. To begin a transaction, we must use the session.beginTransaction() method (Session.beginTransaction()).
Now let’s see the methods of hibernate Transaction Management.
Hibernate Transaction Management methods
-
begin(): It starts a new transaction.
Syntax:
public void begin() throws HibernateException
2. commit(): It ends the transaction and flushes the associated session.
Syntax:
public void commit() throws HibernateException
3. rollback(): It rolls back the current transaction.
Syntax:
public void rollback()throws HibernateException
4. setTimeout(int seconds): It specifies the transaction timeout for any subsequent calls to begin() on this instance.
Syntax:
public void setTimeout(int seconds) throws HibernateException
5. isActive(): It determines whether or not the transaction is still active.
Syntax:
public boolean isActive()throws HibernateException
6. wasRolledBack(): It determines whether or not the transaction was successfully rolled back.
Syntax:
public boolean wasRolledBack()throws HibernateException
6. wasCommitted(): It determines whether or not the transaction was successfully completed.
Syntax:
public boolean wasCommitted()throws HibernateException
7. registerSynchronization(Synchronization synchronization): For this transaction, it registers a user synchronisation callback.
Syntax:
public boolean registerSynchronization(Synchronization synchronization)throws HibernateException
Example
We can use the various methods of hibernate transaction management by using the following pieces of code .
//Here is one example of uses of hibernate Transaction Management methods.
Transaction ty = null;
//Get the session object.
Session session =
HibernateUtil.getSessionFactory().openSession();
try{
ty = session.beginTransaction();
//Perform some operation here
tx.commit();
}catch (HibernateException e) {
if(ty!=null){
ty.rollback();
}
e.printStackTrace();
}finally {
session.close();
}
In hibernate, it is better to rollback the transaction if any exception occurs, so that resources can be free.





