Este contenido no está disponible en el idioma seleccionado.

4.2. Database transaction demarcation


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();
    tx.begin();

    // do some work
    ...

    tx.commit();
}
catch (RuntimeException e) {
    if ( tx != null && tx.isActive() ) tx.rollback();
    throw e; // or display error message
}
finally {
    em.close();
}
Copy to Clipboard Toggle word wrap
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.

4.2.1.1. 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.
Volver arriba
Red Hat logoGithubredditYoutubeTwitter

Aprender

Pruebe, compre y venda

Comunidades

Acerca de la documentación de Red Hat

Ayudamos a los usuarios de Red Hat a innovar y alcanzar sus objetivos con nuestros productos y servicios con contenido en el que pueden confiar. Explore nuestras recientes actualizaciones.

Hacer que el código abierto sea más inclusivo

Red Hat se compromete a reemplazar el lenguaje problemático en nuestro código, documentación y propiedades web. Para más detalles, consulte el Blog de Red Hat.

Acerca de Red Hat

Ofrecemos soluciones reforzadas que facilitan a las empresas trabajar en plataformas y entornos, desde el centro de datos central hasta el perímetro de la red.

Theme

© 2025 Red Hat