Java Reference
In-Depth Information
Transactions and Locking
Transactions and locking are intimately related—the locking techniques chosen to enforce a
transaction can determine both the performance and likelihood of success of the transaction.
The type of transaction selected dictates, to some extent, the type of locking that it must use.
You are not obliged to use transactions if they do not suit your needs, but there is rarely a
good reason to avoid them. If you decide to avoid them, you will need to invoke the flush()
method on the session at appropriate points to ensure that your changes are persisted to the
database.
Transactions
A transaction is a unit of work guaranteed to behave as if you have exclusive use of the data-
base. If you wrap your work in a transaction, the behavior of other system users will not affect
your data. A transaction can be started, committed to write data to the database, or rolled
back to remove all changes from the beginning onward (usually as the result of an error). To
achieve this, you obtain a Transaction object from the database (beginning the transaction)
and manipulate the session as shown in the following code:
Session session = factory.openSession();
try {
session.beginTransaction();
// Normal session usage here...
session.getTransaction().commit();
} catch (HibernateException e) {
Transaction tx = session.getTransaction();
if (tx.isActive()) tx.rollback();
} finally {
session.close();
}
In the real world, it's not actually desirable for all transactions to be fully ACID (see the
sidebar entitled “The ACID Tests”) because of the performance problems that this can cause.
Different database suppliers support and permit you to break the ACID rules to a lesser or
greater extent, but the degree of control over the isolation rule is actually mandated by the
SQL-92 standard. There are important reasons that you might want to break this rule, so both
JDBC and Hibernate also make explicit allowances for it.
Search WWH ::




Custom Search