4.2. Database transaction demarcation

download PDF
Datatabase (or system) transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations. Depending on your isolation level and database capabilities this might not be required but there is no downside if you always demarcate transactions explicitly. You'll have to do operations outside a transaction, though, when you'll need to retain modifications in an EXTENDED persistence context.
An EJB3 application can run in non-managed (i.e. standalone, simple Web- or Swing applications) and managed J2EE environments. In a non-managed environment, an EntityManagerFactory is usually responsible for its own database connection pool. The application developer has to manually set transaction boundaries, in other words, begin, commit, or rollback database transactions itself. A managed environment usually provides container-managed transactions, with the transaction assembly defined declaratively through annotations of EJB session beans, for example. Programmatic transaction demarcation is then no longer necessary, even flushing the EntityManager is done automatically.
Usually, ending a unit of work involves four distinct phases:
  • commit the (resource-local or JTA) transaction (this automatically flushes the entity manager and persistence context)
  • close the entity manager (if using an application-managed entity manager)
  • handle exceptions
We'll now have a closer look at transaction demarcation and exception handling in both managed- and non-managed environments.

4.2.1. Non-managed environment

If an EJB3 persistence layer runs in a non-managed environment, database connections are usually handled by Hibernate's pooling mechanism behind the scenes. The common entity manager and transaction handling idiom looks like this:
// Non-managed environment idiom
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
    tx = em.getTransaction();

    // do some work

catch (RuntimeException e) {
    if ( tx != null && tx.isActive() ) tx.rollback();
    throw e; // or display error message
finally {
You don't have to flush() the EntityManager explicitly - the call to commit() automatically triggers the synchronization.
A call to close() marks the end of an EntityManager. The main implication of close() is the release of resources - make sure you always close and never outside of guaranteed finally block.
You will very likely never see this idiom in business code in a normal application; fatal (system) exceptions should always be caught at the "top". In other words, the code that executes entity manager calls (in the persistence layer) and the code that handles RuntimeException (and usually can only clean up and exit) are in different layers. This can be a challenge to design yourself and you should use J2EE/EJB container services whenever they are available. Exception handling is discussed later in this chapter. EntityTransaction

In a JTA environment, you don't need any extra API to interact with the transaction in your environment. Simply use transaction declaration or the JTA APIs.
If you are using a RESOURCE_LOCAL entity manager, you need to demarcate your transaction boundaries through the EntityTransaction API. You can get an EntityTransaction through entityManager.getTransaction(). This EntityTransaction API provides the regular begin(), commit(), rollback() and isActive() methods. It also provide a way to mark a transaction as rollback only, ie force the transaction to rollback. This is very similar to the JTA operation setRollbackOnly(). When a commit() operation fail and/or if the transaction is marked as setRollbackOnly(), the commit() method will try to rollback the transaction and raise a javax.transaction.RollbackException.
In a JTA entity manager, entityManager.getTransaction() calls are not permitted.
Red Hat logoGithubRedditYoutubeTwitter


Try, buy, & sell


About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.