Hibernate Transaction Management Example

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

transaction management

Transaction Interface in Hibernate

In rest system, we have Transaction interface that characterizes the unit of work. It keeps up deliberation from the exchange usage (JTA,JDBC).

A exchange 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 exchange to rollback.
  4. void setTimeout(int seconds) it sets an exchange break for any exchange begun by an ensuing call to start on this instance.
  5. boolean isAlive() checks if the exchange is still alive.
  6. void registerSynchronization(Synchronization s) registers a client synchronization callback for this transaction.
  7. boolean wasCommited() checks if the exchange is commited successfully.
  8. boolean wasRolledBack() checks if the exchange is rolledback successfully.

Example of Transaction Management in Hibernate

In rest, it is smarter to rollback the exchange if any special case happens, with the goal that assets can be free. How about we see the case of exchange 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