10.3.3. Seam-managed persistence contexts and atomic conversations
Conversation-scoped persistence contexts let you program optimistic transactions spanning multiple server requests, without using
merge()
, reloading data at the beginning of each request, or wrestling with exceptions (LazyInitializationException
or NonUniqueObjectException
).
You can achieve transaction isolation and consistency by using optimistic locking. Both Hibernate and EJB3 make optimistic locking easy with the
@Version
annotation.
By default, the persistence context is synchronized with the database (flushed) at the end of each transaction. Sometimes this is desirable, but often we prefer all changes to be held in memory, and only written to the database when the conversation ends successfully. This allows for truly atomic conversations with EJB3 persistence. However, Hibernate provides this feature as a vendor extension to the
FlushModeType
s defined by the specification. We expect other vendors will soon provide a similar extension.
Seam lets you specify
FlushModeType.MANUAL
when beginning a conversation. Currently, this works only when Hibernate is the underlying persistence provider, but we plan to support other equivalent vendor extensions.
@In EntityManager em; //a Seam-managed persistence context @Begin(flushMode=MANUAL) public void beginClaimWizard() { claim = em.find(Claim.class, claimId); }
Now, the
claim
object remains managed by the persistence context for the entire conversation. We can make changes to the claim:
public void addPartyToClaim() { Party party = ....; claim.addParty(party); }
But these changes will not be flushed to the database until we explicitly force synchronization to occur:
@End public void commitClaim() { em.flush(); }
You can also set the
flushMode
to MANUAL
from pages.xml, for example in a navigation rule:
<begin-conversation flush-mode="MANUAL" />
You can set any Seam-managed persistence context to use manual flush mode:
<components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core"> <core:manager conversation-timeout="120000" default-flush-mode="manual" /> </components>