8.3. Seam-managed persistence contexts
If you're using Seam outside of a Java EE 5 environment, you can't rely upon the container to manage the persistence context lifecycle for you. Even if you are in an EE 5 environment, you might have a complex application with many loosly coupled components that collaborate together in the scope of a single conversation, and in this case you might find that propagation of the persistence context between component is tricky and error-prone.
In either case, you'll need to use a
managed persistence context
(for JPA) or a
managed session
(for Hibernate) in your components. A Seam-managed persistence context is just a built-in Seam component that manages an instance of EntityManager
or Session
in the conversation context. You can inject it with @In
.
Seam-managed persistence contexts are extremely efficient in a clustered environment. Seam is able to perform an optimization that EJB 3.0 specification does not allow containers to use for container-managed extended persistence contexts. Seam supports transparent failover of extended persisence contexts, without the need to replicate any persistence context state between nodes. (We hope to fix this oversight in the next revision of the EJB spec.)
8.3.1. Using a Seam-managed persistence context with JPA
Configuring a managed persistence context is easy. In components.xml
, we can write:
<core:managed-persistence-context name="bookingDatabase"
auto-create="true"
persistence-unit-jndi-name="java:/EntityManagerFactories/bookingData"/>
This configuration creates a conversation-scoped Seam component named bookingDatabase
that manages the lifecycle of EntityManager
instances for the persistence unit (EntityManagerFactory
instance) with JNDI name java:/EntityManagerFactories/bookingData
.
Of course, you need to make sure that you have bound the EntityManagerFactory
into JNDI. In JBoss, you can do this by adding the following property setting to persistence.xml
.
<property name="jboss.entity.manager.factory.jndi.name"
value="java:/EntityManagerFactories/bookingData"/>
Now we can have our EntityManager
injected using:
@In EntityManager bookingDatabase;