Hibernate Transaction is associated with each operation we are performing within a session. We have to use org.hibernate.Transaction class to perform transaction in hibernate.
How Transaction object get initialized ?
As we know translation is associated with the session , so we can initialize Transaction using the beginTransaction() method which is a abstract method in Session interface and returns the Transaction object.
After getting session object we need to call beginTransation()--->
Transaction tx = session.beginTransaction();
And after performing the operation using the session object in the database it needs to committed but in hibernate auto-commit is disable so we need to explicity commit the transation by using the following syntax,
tx.commit();
Note: Transaction commit should be done before closing the session, otherwise it fails to commit. So commit must be done after performing any operation and before closing the session.
Important points regarding Transaction Object
1. It is not thread -safe that means any thread can access this object. So its better to close session after finishing the operation.
2. We can have single commit for multiple operation within a single session. So no need to create multiple Transaction object for each operation within a session.
3. Must commit the database operation otherwise the operation doesn't reflect the changes in the database table and hence hibernate unable to perform the operation.
0 comments:
Post a Comment