Sunday, February 28, 2010

Flush, Persist and Merge

Flush

There are two flush modes -
1) Auto
2) Commit

Auto flush is the default which flushes [persists] the entities in the persistence context at the transaction commit time and also on every query executed with in a transaction. Exception to this is find() because if we want to find an entity which is modified then the find will return back the entity that is present in the persistence context. But if we execute a query then query doesnt return the whole entity but returns some fields as a list and this is the reason that thepersistence context is flushed during query execution.

Commit mode will flush the persistence context when the transaction commits.

We can force flush by calling the flush method on the entity manager to flush the persistence context.


Persist and Merge

Merge can persist but persist cannot merge.
When an entity is persisted and before even the transaction is not commited, we can get the primary key if the primary key is autogenerated using table strategy.

Persistence Context and Entity Manager

Persistence Context is nothing but a bag that holds entities. Entity Manager contains persistence context and manages [creates, updates, deletes] the entities that are part of that persistence context. This is shown in the following figure


The life cycle of persistence context depends on whether it is transaction-scoped or extended persistence context.

Transaction-Scoped Persistence Context -

Transaction begins when the bean method is invoked and it ends when the method returns or completes. Similarly transaction-scoped persistence context follows the transaction and is created when the transaction begins and ends after the transaction commits or rolls back.



Extended Persistence Context -

This type of Persistence Context is independent of transaction i.e., the creation or destruction of persistence context is not dependent on transaction begin or transaction end as in the case of transaction-scoped persistence context. Persistence Context will be created when the statefull session bean is created and it is destroyed when the stateful session bean is destroyed.



Note:

There can be many instances of Entity Manager referring to the same single instance of persistence context if all these entity managers are part of the same transaction i.e., entity manager instances part of different ejb's invoked by an ejb which starts and ends the transaction. Please refer the picture below -