Understanding transaction in hibernate

Any time you want Hibernate to manage the persistence of your JavaBeans, you must first initiate a transaction, which is just a simple method call on the Hibernate Session.

hibernateSession.beginTransaction();

Once you being a transaction, you can start associating your POJOs and JavaBeans with the Hibernate Session. If you don’t initiate a transaction, you’ll get a runtime exception telling you about no transactional context being in existence, and at all costs, we want to avoid runtime exceptions.
Now, the really cool thing about Hibernate is the fact that once a transaction has been started, all you have to do is associate an instance with the Session, and then Hibernate will take care of fully managing the persistent state of that instance, right up to and including the point where you commit the transaction. When you finally commit the transaction, the state of all of the POJO’s that have been associated with the Hibernate Session will be saved to the database.
The following snippet of code demonstrates the art of beginning a transaction, creating an instance, associating that instance with the Hibernate Session, and then finally, committing the transaction:

hibernateSession.beginTransaction();
User user = new User();
hibernateSession.saveOrUpdate(user);
hibernateSession.getTransaction().commit();

In this code snippet, a new transaction is created, after which a brand new, unassociated, transient instance of a User is created. This instance is then associated with the Hibernate Session when it is passed as an argument to the saveOrUpdate() method of the session, transitioning the instance from being a transient instance, to a persistent instance

Attended Any Interviews ? Please send us Questions to faqs@javastuff.in