Hibernate Transaction Management Example

A transaction basically represents to a unit of work. In such case, on the off chance that one stage comes up short, the entire transaction fizzles (which is named as atomicity). An transaction can be portrayed by ACID properties (Atomicity, Consistency, Isolation and Durability).

transaction management

Transaction Interface in Hibernate

In hibernate framework, we have Transaction interface that characterizes the unit of work. It keeps up deliberation from the transaction usage (JTA,JDBC).

A transaction is related with Session and instantiated by calling session.beginTransaction().

The techniques for Transaction interface are as follows:

  1. void begin() begins another transaction.
  2. void commit() closes the unit of work except if we are in FlushMode.NEVER.
  3. void rollback() powers this transaction to rollback.
  4. void setTimeout(int seconds) it sets an transaction break for any transaction begun by an ensuing call to start on this instance.
  5. boolean isAlive() checks if the transaction is still alive.
  6. void registerSynchronization(Synchronization s) registers a client synchronization callback for this transaction.
  7. boolean wasCommited() checks if the transaction is commited successfully.
  8. boolean wasRolledBack() checks if the transaction is rolledback successfully.

Example of Transaction Management in Hibernate

In hibernate, it is smarter to rollback the transaction if any special case happens, with the goal that assets can be free. How about we see the case of transaction the board in hibernate.

  1. Session session = null;  
  2. Transaction tx = null;  
  3.   
  4. try {  
  5. session = sessionFactory.openSession();  
  6. tx = session.beginTransaction();  
  7. //some action  
  8.   
  9. tx.commit();  
  10.   
  11. }catch (Exception ex) {  
  12. ex.printStackTrace();  
  13. tx.rollback();  
  14. }  
  15. finally {session.close();}  





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition