Hibernate Transaction object


Hibernate Transaction object

The term "transaction" refers to a unit of labour. Whenever one of these steps fails, the transaction as a whole fails (which is termed as atomicity). ACID attributes can be used to describe a transaction (Atomicity, Consistency, Isolation and Durability).

Hibernate Transaction Interface

Hibernate provides a transactional interface for managing data.

Transaction interface defines the unit of work in the Hibernate framework. It maintains abstraction from the implementation of transactional rules. (JTA,JDBC).

Sessions are related with transactions, which can be created by calling session.beginTransaction().

The Transaction interface has the following methods:

  • Starts a new transaction using the void begin() method.
  • Unless we are in FlushMode, the unit of work is terminated by calling void commit().
  • Transaction rollback is forced by calling the void rollback() method, which returns null.
  • Instance of the setTimeout class (int seconds) Any transaction begun by a subsequent call to begin on this instance will be timed out.
  • isAlive() returns a boolean value that indicates whether or not the transaction is still active.
  • A user synchronisation callback is registered for this transaction with the help of registerSynchronization(Synchronization s).
  • Checks whether the transaction has been successfully committed using the boolean value wasCommited().
  • If the transaction was successfully rolled back, wasRollback() boolean function returns true.

Hibernate Transaction Management Example

The transaction should be rolled back when an exception occurs in hibernation, so that resources can be freed. Let's have a look at hibernate's transaction management sample.

Session session = null;  
Transaction tx = null;  
try {  
session = sessionFactory.openSession();  
tx = session.beginTransaction();  
tx.commit();  
}catch (Exception ex) {
   ex.printStackTrace();  
tx.rollback();  
}  
finally {session.close();}