Hibernate Transaction Management
A transaction simply represents a unit of work. In such case, if one step fails, the whole transaction fails (which is termed as atomicity). A transaction can be described by ACID properties (Atomicity, Consistency, Isolation and Durability).Transaction Interface in Hibernate
In hibernate framework, we have Transaction interface that defines the unit of work. It maintains abstraction from the transaction implementation (JTA,JDBC).A transaction is associated with Session and instantiated by calling session.beginTransaction().
The methods of Transaction interface are as follows:
- void begin() starts a new transaction.
- void commit() ends the unit of work unless we are in FlushMode.NEVER.
- void rollback() forces this transaction to rollback.
- void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
- boolean isAlive() checks if the transaction is still alive.
- void registerSynchronization(Synchronization s) registers a user synchronization callback for this transaction.
- boolean wasCommited() checks if the transaction is commited successfully.
- boolean wasRolledBack() checks if the transaction is rolledback successfully.
Example of Transaction Management in Hibernate
This is the basic structure that your Hibernate programs should have, conserning transaction handling:Session session = null;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.
Transaction tx = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
tx.setTimeout(5);
tx.commit();
}catch(RuntimeException e){
try{
tx.rollback();
}catch(RuntimeException rbe){
rbe.printStackTrace();
tx.rollback();
}
throw e;
}finally{
if(session!=null){
session.close();
}
}
}
Hope we are able to explain you Hibernate Transaction Management, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).
Please share us on social media if you like the tutorial.
Source:http://www.tutorialsdesk.com/2014/11/hibernate-transaction-management.html
Tidak ada komentar:
Posting Komentar