Trying to figure out some possible situations, when a EntityManagerFactory could be useful in EJB. Of course usually one needs just an transaction-scoped EntityManager (JTA scoped), so that all injected EntityManagers share the same PersistenceContext.
What happens in the following situations:
-
When
@PersistenceContext(type=PersistenceContextType.EXTENDED)is used: is this JTA-enabled? will the requests of such an EntityManager be executed in the context of the JTA? If not, that in which one? (Note: of course it works only with@StatefulEJBs). Of course it is clear, that in this case the EntityManager will have its own/special PersistenceContext. -
When one uses
@PersistenceUnitto get aEntityManagerFactoryin an EJB (I suppose it works in all type of EJBs, correct?), is the obtainedEntitymanagerJTA-enabled (of courseEntitymanager.joinTransaction()is necessary)? How can one get a transaction-scoped (JTA enabled) or Extended EntityManager from the Factory? When would be useful to use the Factory, instead of a Entitymanager. (Of course it is clear that an EntityManagerFactory is the only interface for a Java SE application to the JPA, but what about EJB?).
Your questions revolve around the assumption that you are put in a situation were you are obliged to inject @PersistenceUnit to get a EntityManagerFactory in an EJB. Well… let me narrate some missing background here:
In servlets
We had to follow these steps in order to instantiate an EntityManager:
The above 2 steps quarantees the EntityManager is local to the current thread thus thread-safe. This scenario was a workaround for servlets being re-entrant with respect to the container injection. Meaning the servlet will accept already existing entityManagers to be injected by the container.
In EJBs
By definition, EJBs are non-reentrant with respect to the container injection, thus we know that the container will instantiate a fresh entityManager proxy local for the EJB, thus thread-safe.
That said we can take the discussion into how/when to use Extended PersistenceContext
Quoting the JSR-317 of the JPA specifications page 294:
Thus the non-reentrancy feature can be broke using the attribute PersistenceContextType.EXTENDED only to serve the stateful session bean semantics. It is mandatory for the stateful session bean to maintain the very same EntityManager as long as it exists.
To conclude
In your first question:
the answer is: It is not useful.
As for your second question I am sure the first answer and the above background narration discards the need to ask it in the first place!