Conversational Persistence Contexts
Entity managers participate in transactions just like any other
resource. We’ve seen examples of this throughout this book. Extended
persistence contexts have some interesting transactional behavior that you
can exploit. You are allowed to invoke EntityManager
operations such as persist(),
merge(), and remove() outside of a transaction when you
interact with an extended persistence context. These inserts, updates, and
deletes are queued until the extended persistence context is enlisted in
an active transaction and is committed. In other words, the database is
not touched until the persistence context becomes involved with a
transaction. Also, any executed queries do not hold their database
connection after they complete. Let’s look at an example of this:
1 EntityManager manager = entityManagerFactory.createEntityManager(EXTENDED); 2 manager.persist(entityA); 3 manager.merge(entityB); 4 manager.remove(entityC); 5 userTransaction.begin(); 6 manager.flush(); 7 userTransaction.commit();
Line 1 creates an extended persistence context. Lines 2–4 create,
update, and delete some entity beans. These actions are queued until the
persistence context becomes enlisted in a transaction in Line 5. The act
of calling an EntityManager method
enlists the persistence context in the transaction. The batched actions
are then committed in Line 7.
You can really exploit this behavior by using it with stateful session beans.
The combination of stateful session beans, extended ...