Java Reference
In-Depth Information
Hibernate treats the isolation as a global setting—you apply the configuration option
hibernate.connection.isolation in the usual manner, setting it to one of the values permitted
in Table 8-2. This is not always ideal. You will sometimes want to treat one particular trans-
action at a high level of isolation (usually Serializable), while permitting lower degrees of
isolation for others. To do so, you will need to obtain the JDBC connection directly, alter the
isolation level, begin the transaction, roll back or clean up the transaction as appropriate, and
reset the isolation level back to its original value before releasing the connection for general
usage. Hibernate does not provide a more direct way to alter the isolation level of the connec-
tion in a localized way. The implementation of the createUser() method, shown in Listing 8-1,
demonstrates the additional complexity that the connection-specific transaction isolation
involves.
Listing 8-1. Using a Specific Isolation Level
public static void createUser(String username)
throws HibernateException
{
Session session = factory.openSession();
int isolation = -1;
try {
isolation = session.connection().getTransactionIsolation();
session.connection().setTransactionIsolation(
Connection.TRANSACTION_SERIALIZABLE);
session.beginTransaction();
// Normal usage of the Session here...
Publisher p = new Publisher(username);
Subscriber s = new Subscriber(username);
session.saveOrUpdate(p);
session.saveOrUpdate(s);
// Commit the transaction
session.getTransaction().commit();
} catch (SQLException e1) {
rollback(session);
throw new HibernateException(e1);
} catch (HibernateException e1) {
rollback(session);
throw e1;
} finally {
// reset isolation
reset(session,isolation);
// Close the session
close(session);
}
}
Search WWH ::




Custom Search