Java Reference
In-Depth Information
These worries are addressed by using a transaction manager to coordinate the
transaction across multiple resources using a robust transaction protocol known as a
two-phase commit . Writing a transaction manager to coordinate a two-phase commit is
complicated and error prone. Luckily, robust open source transaction manager imple-
mentations are available.
JTA
The Java Transaction API ( JTA ) is the Java EE implementation of the XA two-phase com-
mit API . It defines an API for resources to communicate with the transaction manager,
and also an API for applications to control transaction boundaries programmatically.
JTA is the accepted standard for Java transaction managers.
DECLARATIVE TRANSACTIONS
Even with the support provided by the basic JTA , coordinating transactions can be
time consuming and fragile. Rollbacks and commits need to be made in code, leaving
the chance that some code paths, particularly unexpected exits, could fail to complete
the transactions properly.
The process of handling transactions is made much simpler for container-managed
declarative transactions. Transaction boundaries are declared simply in metadata and
the container handles creating the transactions and managing failure cases. Container-
managed transactions are so useful that they're arguably among the key attractions of
application servers.
Updating an inventory with application-managed transactions
To see the difference, let's have a look at how the InventoryImpl implementation to
persist a Food object would look if it were using application-managed persistence (and
by extension application-managed transactions):
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction tx = em.getTransaction();
em.getTransaction().begin();
try {
em.persist(food);
em.getTransaction().commit();
} catch (PersistenceException e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
} finally {
em.close();
}
Not much fun, is it? Everything that's being done by hand here was automatically han-
dled for you by the container (with much less hand-wringing and debugging) in sec-
tion 3.2.4.
3.3.2
Handling multipart transactions
You may be feeling slightly suspicious about transactions you can't see and didn't do
much work to create. Is the single line <tx:transaction method="*" value=
Search WWH ::




Custom Search