Managing Transactions with Hibernate - Transactions: Core APIs
(Page 2 of 4 )
The core of transactions in Hibernate is the transaction interface. This interface is implemented to provide three of the in-built classes that do the real work(communication and transaction management at database/JTA level). A transaction object is always associated with a session object. To instantiate a transaction object, beginTransaction() is called on the session object. For example if session is the session object then:
Transaction tcx=session.beginTransaction();
The above statement would instantiate a transaction object represented by tcx. Many instances of transaction can be retrieved using same session object as a session (not class) can span many transactions (not classes). There are three implementations of the transaction interface provided by Hibernate. They are:
a. JDBCTransaction
b. JTATransaction
c. CMTTransaction
Of these, JDBCTransaction is the default. That means if hibernate.transaction_factory key’s value is not set in the hibernate.properties file, the transaction object returned by the beginTransaction() method is the object of the JDBCTransaction class. The main methods of the transaction interface are commit() and rollback().
Since many transactions can take place within a conversation, the concept of savepoints is not required. The functionality is provided by the concept of multiple transactions within the session. Here are the details of the methods:
Commit() is one of the two methods used to end a transaction. It also flushes the session associated with it. Commit() internally commits the underlying transaction. So just calling the save() method on the session object wouldn’t persist (save) the data contained in the ORM object into the database. One more point to keep in mind is that the underlying transaction is committed if and only if the transaction was initiated by the calling object.
Rollback(), as its name suggests, rolls back the underlying transaction. So to start a transaction and then commit it, the statements would be:
Transaction tcx=session.beginTransaction();
//..save, update, delete retrieve statements
tcx.commit();
That’s all you need to know about methods of transaction. In the next section I will be discussing the thread-local pattern and how to use it to create a Factory class that would encapsulate most of the initialization steps in using Hibernate.
Next: Hibernate in the Real World: Implementing a Utility class for Hibernate >>
More Java Articles
More By A.P.Rajshekhar