Transaction in hibernate

What is Transacton in general?


A Transaction represents a unit of work performed within the database management system against a database.

We generally group the related work within one transaction so that if part of the work is failed then entire transaction should be failed.

Transaction has 4 main properties (ACID)


ACID stands for Atomicity,Consistency,Isolation and Durability

Atomicity

If one part of the transaction fails, then Atomicity ensures that entire transaction fails so that database state is left unchanged.

So Atomicity does either entire operation success or no operation success.

Consistency

This will ensures that transaction will bring the database from one valid state to another valid state.

Any data written to the database must be valid according to all defined rules, including constraints,cascades, triggers etc.

So transaction either creates a new and valid state of data, or, if any failure occurs, returns all data to its state before the transaction was started.

Isolation

A transaction which is in progress and not yet committed must remain isolated from any other transaction in the system.

Durability

It ensures that once a transaction has been committed, it will remain permanently in the system.

Transaction in Hibernate


A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction().

A single session might span multiple transactions However, it is intended that there will be at most one uncommitted Transaction associated with a particular Session at any time.

Methods used in Hiernate transaction


public void begin() : It starts a new transaction

public void commit() : This method will commit the associated transaction

public void rollback() : This method will force the underlying transaction to roll back

It can be used whenever some exception occurred.

public boolean isActive() : This method will return true if the local transaction is still active,false otherwise

public void setTimeout(int seconds) : This method will set the transaction timeout for any transaction started by a subsequent call to begin() on this instance

public boolean wasCommitted() : This method will check if the transaction is commited successfully or not.

public boolean wasRolledBack() : This method will check if the transaction is rolledback successfully or not.

Transaction in hibernate example


It is advisable to handle the exception and rollback the transaction in catch block as shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Session session = null;  
Transaction tx = null;  
  
try {  
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();  
tx.setTimeout(5);
//some code to execute within transaction  
  
tx.commit();  
  }
catch (Exception ex) {  
try{
        tx.rollback();
    }catch(Exception exception){
        log.error("Couldn’t roll back the transaction", exception);
    }
    throw ex;
}  
finally{
if(session!=null)
{
session.close();
}
}
Session session = null;  
Transaction tx = null;  
  
try {  
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();  
tx.setTimeout(5);
//some code to execute within transaction  
  
tx.commit();  
  }
catch (Exception ex) {  
try{
		tx.rollback();
	}catch(Exception exception){
		log.error("Couldn’t roll back the transaction", exception);
	}
	throw ex;
}  
finally{
if(session!=null)
{
session.close();
}
}

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on