Hibernate Transaction Handle Example
This tutorial is going to talk about the basics of Hibernate Transactions and Sessions. As we know modern database systems use the notion of Transaction and Session in order to define a group of data accessing operations. When multiple users access the same database data, the system has to ensure that all the operations are going to be executed normally and the database will end up in a consistent state.
1. Unit Of Work – Session
A unit of work is, as we said, a group of database operations. Hibernate uses Session to express the notion of the unit of work. In order to begin a Unit of Work you have to open a Session and to end it you have to close a Session. Session is basically a cache and an interface for all the operation the user wants to do in a database.
2. Transaction
A Transaction is also a group of operations over a database but it defines the very boundaries of these operations. A transactions has a begining, a set of operations that will all be executed correctlly or else none of them will be executed at all, and finally an end. When a database system has to handle many transactions, it is responsible to optimize the chronicle of the different operations and ensure its correctness. In Hibernate no operations can happen out of the scope of a transaction. To manage transactions Hibernate also uses JTA (Java Transaction API). When using JTA all database connections are part of the global JTA transaction.
3. Example
This is the basic structure that your Hibernate programs should have, conserning transaction handling:
Session session = null; Transaction tx = null; try{ session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); tx.setTimeout(5); //doSomething(session); tx.commit(); }catch(RuntimeException e){ try{ tx.rollback(); }catch(RuntimeException rbe){ log.error("Couldn’t roll back transaction", rbe); } throw e; }finally{ if(session!=null){ session.close(); } }
Here as you can see whenever a RuntimeException happens we call rollback()
API call that forces the rollback of the transaction. This means that every operation of that specific transaction that occured before the Exception, will be canceled and the database will return in its state before these operations took place.
Useful links:
- Transactions and Concurrency
- Sessions and transactions
- Transaction API
- Hibernate Session
- Java Transaction API
This was an example on Hibernate Transaction Handle.