Hibernate Framework : ORM Tool :: Hibernate Transaction
Transaction Intro? |
Transaction
- A Transaction is unit of work that is made up of a set of operations, which are performed to a database tables. In an Online Banking System, for transferring funds from one account to another account, you need to enter certain details, such as username and transaction password, and the amount to transfer.
- If the transaction is successful, the amount in your account is debited and that amount is credited to the specified account. However, in case the transaction fails, an undo operation needs to performed to bring the transaction in the initial state.
- In a database system, a transaction consists of one or more SQL queries, where each query performs specific read/write operations to a database table.
Each transaction consists of the following steps
- Transaction begins.
- Required data manipulation and queries, such as insert , update and delete, are performed.
- if the data manipulation is successfully executed, then it is committed. On the other hand, if an error occurs, then the manipulation are rolled back so that the related data is set back to its original or initial state.
The Transaction ends automatically once manipulation are successfully committed or rollbacked.
Transaction States
- Active : This is the initial state. The transaction stay in this state while it is executing. and it is ready for execution.
- Partially Committed : Represents the last state of the transaction. it denotes that the transaction has already performed its final operation.
- Failed : implied that the transaction has failed and can not proceed further.
- Aborted : The state after the transaction has been rolled back and the database has been restored to its state prior to the start of the transaction.
- Committed : Represents the successful completion of the transaction.
- Terminated: Represents either transaction is committed or aborted
Note:- We cannot abort or rollback a committed transaction.
ACID Properties
When a transaction processing system creates a transaction, it will ensure that the transaction will have certain characteristics. The developers of the components that comprise the transaction are assured that these characteristics are in place. They do not need to manage these characteristics themselves. These characteristics are known as the ACID properties. ACID is an acronym for atomicity, consistency, isolation, and durability.
- Atomicity : The atomicity property identifies that the transaction is atomic. An atomic transaction is either fully completed, or is not begun at all. Any updates that a transaction might affect on a system are completed in their entirety. If for any reason an error occurs and the transaction is unable to complete all of its steps, the then system is returned to the state it was in before the transaction was started. An example of an atomic transaction is an account transfer transaction. The money is removed from account A then placed into account B. If the system fails after removing the money from account A, then the transaction processing system will put the money back into account A, thus returning the system to its original state. This is known as a rollback.
- Consistency : A transaction enforces consistency in the system state by ensuring that at the end of any transaction the system is in a valid state. If the transaction completes successfully, then all changes to the system will have been properly made, and the system will be in a valid state. If any error occurs in a transaction, then any changes already made will be automatically rolled back.
- Isolation : Refers that each transaction must be hidden from all other transactions. It Means that no other transactions are allowed to view or acccess the data involved in the execution of a transaction.
- Durability : A transaction is durable in that once it has been successfully completed, all of the changes it made to the system are permanent.
Transaction isolation levels are a measure of the extent to which transaction isolation succeeds. In particular, transaction isolation levels are defined by the presence or absence of the following phenomena:
- Dirty Reads : A dirty read occurs when a transaction reads data that has not yet been committed. For example, suppose transaction 1 updates a row. Transaction 2 reads the updated row before transaction 1 commits the update. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed.
- Nonrepeatable Reads: A nonrepeatable read occurs when a transaction reads the same row twice but gets different data each time. For example, suppose transaction 1 reads a row. Transaction 2 updates or deletes that row and commits the update or delete. If transaction 1 rereads the row, it retrieves different row values or discovers that the row has been deleted.
- Phantoms : A phantom is a row that matches the search criteria but is not initially seen. For example, suppose transaction 1 reads a set of rows that satisfy some search criteria. Transaction 2 generates a new row (through either an update or an insert) that matches the search criteria for transaction 1. If transaction 1 reexecutes the statement that reads the rows, it gets a different set of rows.
The four transaction isolation levels (as defined by SQL-92) are defined in terms of these phenomena. In the following table, an "X" marks each phenomenon that can occur.
Transaction isolation level | Dirty reads | Nonrepeatable reads | Phantoms |
---|---|---|---|
Read uncommitted | X | X | X |
Read committed | — | X | X |
Repeatable read | — | — | X |
Serializable | — | — | — |
The following table describes simple ways that a DBMS might implement the transaction isolation levels.
Transaction isolation | Possible implementation |
---|---|
Read uncommitted | Transactions are not isolated from each other. If the DBMS supports other transaction isolation levels, it ignores whatever mechanism it uses to implement those levels. So that they do not adversely affect other transactions, transactions running at the Read Uncommitted level are usually read-only. |
Read committed | The transaction waits until rows write-locked by other transactions are unlocked; this prevents it from reading any "dirty" data. The transaction holds a read lock (if it only reads the row) or write lock (if it updates or deletes the row) on the current row to prevent other transactions from updating or deleting it. The transaction releases read locks when it moves off the current row. It holds write locks until it is committed or rolled back. |
Repeatable read | The transaction waits until rows write-locked by other transactions are unlocked; this prevents it from reading any "dirty" data. The transaction holds read locks on all rows it returns to the application and write locks on all rows it inserts, updates, or deletes. For example, if the transaction includes the SQL statement SELECT * FROM Orders, the transaction read-locks rows as the application fetches them. If the transaction includes the SQL statement DELETE FROM Orders WHERE Status = ‘CLOSED’, the transaction write-locks rows as it deletes them. Because other transactions cannot update or delete these rows, the current transaction avoids any nonrepeatable reads. The transaction releases its locks when it is committed or rolled back. |
Serializable | The transaction waits until rows write-locked by other transactions are unlocked; this prevents it from reading any "dirty" data. The transaction holds a read lock (if it only reads rows) or write lock (if it can update or delete rows) on the range of rows it affects. For example, if the transaction includes the SQL statement SELECT * FROM Orders, the range is the entire Orders table; the transaction read-locks the table and does not allow any new rows to be inserted into it. If the transaction includes the SQL statement DELETE FROM Orders WHERE Status = ‘CLOSED’, the range is all rows with a Status of "CLOSED"; the transaction write-locks all rows in the Orders table with a Status of "CLOSED" and does not allow any rows to be inserted or updated such that the resulting row has a Status of "CLOSED". Because other transactions cannot update or delete the rows in the range, the current transaction avoids any nonrepeatable reads. Because other transactions cannot insert any rows in the range, the current transaction avoids any phantoms. The transaction releases its lock when it is committed or rolled back. |
Now, let us know how to handle transation in Hibernate 3.2
Hibernate Transaction API |
- As Hibernate uses Java Database Connectivity (JDBC) connections and Java Transaction API (JTA) resources to execute transactions, you need to configure these( JDBC / JTA ) in a Hibernate Configuration file.
- In Addition, the Hibernate O/R Mapping framework provides the Transaction interface that allows you to handle transactions in a hibernate application.
- A Hibernate application can run in non-managed (i.e., standalone, simple Web- or Swing applications) and managed J2EE environments. In a non-managed environment, Hibernate is usually responsible for its own database connection pool. The application developer has to manually set transaction boundaries (begin, commit, or rollback database transactions) themselves. A managed environment usually provides container-managed transactions (CMT), with the transaction assembly defined declaratively (in deployment descriptors of EJB session beans, for example). Programmatic transaction demarcation is then no longer necessary.
Ending a Session usually involves four distinct phases:
- flush the session
- commit the transaction
- close the session
- handle exceptions
Non-managed environment
If a Hibernate persistence layer runs in a non-managed environment, database connections are usually handled by simple (i.e., non-DataSource) connection pools from which Hibernate obtains connections as needed.
The session/transaction handling idiom looks like this:
// Non-managed environment idiom
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
// do some work
...
tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
You do not have to flush() the Session explicitly: the call to commit() automatically triggers the synchronization depending on the
USing JTA
If your persistence layer runs in an application server (for example, behind EJB session beans), every datasource connection obtained by Hibernate will automatically be part of the global JTA transaction. You can also install a standalone JTA implementation and use it without EJB. Hibernate offers two strategies for JTA integration.If you use bean-managed transactions (BMT), Hibernate will tell the application server to start and end a BMT transaction if you use the Transaction API. The transaction management code is identical to the non-managed environment.
// BMT idiom
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
// do some work
...
tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
If you want to use a transaction-bound Session, that is, the getCurrentSession() functionality for easy context propagation, use the JTA UserTransaction API directly:
// BMT idiom with getCurrentSession()
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work on Session bound to transaction
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
With CMT, transaction demarcation is completed in session bean deployment descriptors, not programmatically. The code is reduced to:
// CMT idiom
Session sess = factory.getCurrentSession(); // do some work …
In a CMT/EJB, even rollback happens automatically. An unhandled RuntimeException thrown by a session bean method tells the container to set the global transaction to rollback. You do not need to use the Hibernate Transaction API at all with BMT or CMT, and you get automatic propagation of the “current” Session bound to the transaction.
Exception handling
If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable. Ensure that the Session will be closed by calling close() in a finally block.
The HibernateException, which wraps most of the errors that can occur in a Hibernate persistence layer, is an unchecked exception. Hibernate wraps SQLExceptions thrown while interacting with the database in a JDBCException. In fact, Hibernate will attempt to convert the exception into a more meaningful subclass of JDBCException.
The standard JDBCException subtypes are:
- JDBCConnectionException: indicates an error with the underlying JDBC communication.
- SQLGrammarException: indicates a grammar or syntax problem with the issued SQL.
- ConstraintViolationException: indicates some form of integrity constraint violation.
- LockAcquisitionException: indicates an error acquiring a lock level necessary to perform the requested operation.
- GenericJDBCException: a generic exception which did not fall into any of the other categories.
Transaction timeout
An important feature provided by a managed environment like EJB, that is never provided for non-managed code, is transaction timeout.
Session sess = factory.openSession();
try {
//set transaction timeout to 3 seconds
sess.getTransaction().setTimeout(3);
sess.getTransaction().begin();
// do some work
...
sess.getTransaction().commit()
}
catch (RuntimeException e) {
sess.getTransaction().rollback();
throw e; // or display error message
}
finally {
sess.close();
}
setTimeout() cannot be called in a CMT bean, where transaction timeouts must be defined declaratively.
Hibernate Transaction Example |
Click the Image to download the code
Directory Stucture of hiberate Transaction Application
Item Bean Class
Item hibernate mapping file
Hibernate Configuration File
TestDrive class as a Client Program
Hibernate Generated Query
Hibernate: select item0_.itemId as col_0_0_ from ItemDetails item0_ where itemid<3
ItemId ItemName Qty
Hibernate: select item0_.itemId as itemId0_0_, item0_.itemName as itemName0_0_, item0_.qty as qty0_0_ from ItemDetails item0_ where item0_.itemId=?
1 Park Avenue 1000
Hibernate: select item0_.itemId as itemId0_0_, item0_.itemName as itemName0_0_, item0_.qty as qty0_0_ from ItemDetails item0_ where item0_.itemId=?
2 new lux 99900
Hibernate: update ItemDetails set qty=? where itemId=?
Rows affected/Updated : 1
Inserting New Record
Hibernate: select max(itemId) from ItemDetails
Hibernate: insert into ItemDetails (itemName, qty, itemId) values (?, ?, ?)
Table after Transaction
mysql> select * from itemDetails;
+--------+-------------+-------+
| itemId | itemName | qty |
+--------+-------------+-------+
| 1 | Park Avenue | 1000 |
| 2 | new lux | 99900 |
| 3 | Dove | 500 |
| 4 | Cinthol | 1900 |
+--------+-------------+-------+
4 rows in set (0.00 sec)
Table Before Transaction
mysql> select * from itemDetails;
+--------+-------------+-------+
| itemId | itemName | qty |
+--------+-------------+-------+
| 1 | Park Avenue | 800 |
| 2 | new lux | 99900 |
| 3 | Dove | 500 |
+--------+-------------+-------+
3 rows in set (0.00 sec)
Download Examples |
Click the below Link to download complete Example
Recent Comments