Java Reference
In-Depth Information
@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface PersistenceContext {
public String name() default "";
public String unitName() default "";
public PersistenceContextType type() default
PersistenceContextType.TRANSACTION;
public PersistenceProperty[] properties() default {};
}
The first element of the annotation,
name
, specifies the JNDI name of the persistence
context. This element is used in the unlikely case that you must explicitly mention the
JNDI name for a given container implementation to be able to look up an
EntityMan-
ager
. In most situations, leaving this element empty is fine, except when you use
@Persistence-Context
at the class level to establish a reference to the persistence
context.
The
unitName
element specifies the name of the persistence unit. A persistence unit is a
grouping of entities used in an application. The idea is useful when you have a large Java
EE application and would like to separate it into several logical areas (think Java packages).
For example, ActionBazaar entities could be grouped into
general
and
admin
units.
Persistence units can't be set up using code; you must configure them through the
per-
sistence.xml
deployment descriptor. We cover configuration of persistence units in
a specific persistence unit—for example,
admin
in ActionBazaar—you'd specify the unit
as follows:
@PersistenceContext(unitName="admin")
EntityManager entityManager
In the event that a Java EE module has a single persistence unit, specifying the
unitName
might seem redundant. Most persistence providers will resolve the unit correctly if you
don't specify a
unitName
. But it's good practice to specify the
unitName
because the
specification isn't clear on the behavior if one isn't provided.
EntityManager scoping
The element type specifies the
EntityManager
scope. As noted, for a container-man-
aged
EntityManager
, scope can be either transaction or extended. If the type attribute