Java Reference
In-Depth Information
isn't specified, the scope defaults to TRANSACTION . So, not surprisingly, the typical usage
of the type element is to specify EXTENDED for an EntityManager . The code would
like the following:
@PersistenceContext(type=PersistenceContexType.EXTENDED)
EntityManager entityManager;
You aren't allowed to use extended persistence scope for stateless session beans or MDBs.
The reason is pretty obvious, because the purpose of the extended scope is to extend across
method invocations on a bean, even if each method invocation is a separate transaction. Be-
cause neither stateless session beans nor MDBs are supposed to implement such functional-
ity, it makes no sense to support extended scope for these bean types. On the other hand, ex-
tended persistence scope is ideal for stateful session beans. An underlying EntityMan-
ager with extended scope could be used to cache and maintain the application domain
across an arbitrary number of method invocations from the client. More importantly, this
can be done without giving up on method-level transaction granularity (most likely using
CMT).
Note
The real power of container-managed EntityManager s lies in the high degree of ab-
straction they offer. Behind the scenes, the container instantiates EntityManager s,
binds them to JNDI, injects them into beans on demand, and closes them when they're no
longer needed (typically when a bean is destroyed).
It's difficult to appreciate the amount of menial code the container takes care of until you
see the alternative. Keep this in mind when looking at the next section on directly accessing
the EntityManagerFactory . Note that EntityManager s aren't thread-safeā€”this
means that special care must be taken when injecting EntityManager s into CDI beans,
servlets, JSF beans, and the like.
EntityManagers and thread safety
EntityManager s aren't thread-safe and shouldn't be used in situations where more than
one thread may access them. This means that it's dangerous to use EntityManager s in
servlets or JSP pages. A servlet is instantiated once and handles multiple requests concur-
rently. Although the application may appear to work correctly in development or in light
Search WWH ::




Custom Search