Introduction to Java Persistence API

This section introduces concepts of Java Persistence API and provides general information on it.

What Is Java Persistence API?

The Java Persistence API (JPA) is a lightweight framework for Java persistence (see Persisting Objects) based on Plain Old Java Object (POJO). JPA is a part of EJB 3.0 and 3.1 specifications. JPA provides an object relational mapping approach that lets you declaratively define how to map Java objects to relational database tables in a standard, portable way. You can use this API to create, remove and query across lightweight Java objects within both an EJB 3.0/3.1-compliant container and a standard Java SE 5/6 environment.

What Do You Need to Develop with JPA

Relational Database

To develop your applications with JPA, you can use any relational database.

Domain Model Classes

Your domain model should consist of classes representing entities–lightweight persistent domain objects. The easiest way to define an entity class is by using the @Entity annotation (see Using Metadata Annotations), as the following example shows:

Object Relational Mapping Metadata

Metadata Annotations and ORM.xml File

A metadata annotation represents a Java language feature that lets you attach structured and typed metadata to the source code. Annotations alone are sufficient for the metadata specification–you do not need to use XML. Annotations for object relational mapping are in the javax.persistence package. For more information and examples, see Chapter 8 "Metadata Annotations" of the JPA Specification

An object relational mapping XML file is optional. If you choose to provide one, then it should contain mapping information for the classes listed in it. The persistence provider loads an orm.xml file (or other mapping file) as a resource. If you provide a mapping file, the classes and mapping information specified in the mapping file will be used. For more information and examples, see the following:

Advantages and Disadvantages of Using Annotations

Metadata annotations are relatively simple to use and understand. They provide in-line metadata located with the code that this metadata is describing–you do not need to replicate the source code context of where the metadata applies.

On the other hand, annotations unnecessarily couple the metadata to the code. Thus, changes to metadata require changing the source code.

Advantages and Disadvantages of Using XML

The following are advantages of using XML:

no coupling between the metadata and the source code;

compliance with the existing, pre-EJB 3.0 development process;

support in IDEs and source control systems;

The main disadvantages of mapping with XML are the complexity and the need for replication of the code context.

Persistence Provider

The persistence provider supplies the implementation of the JPA specification.

The persistence provider handles the object relational mapping of the relationships, including their loading and storing to the database (as specified in the metadata of the entity class), and the referential integrity of the relationships (as specified in the database).

For example, the EclipseLink persistence provider ensures that relational descriptors are created for annotated objects, as well as mappings are created based on annotations.

Persistence Application Code

To manage entities (see Domain Model Classes) in your persistence application, you need to obtain an entity manager from an EntityManagerFactory. How you get the entity manager and its factory largely depends on the Java environment in which you are developing your application.

Application-Managed Entity Manager

In the Java SE environment, not the container but the application manages the life cycle of an entity manager. You would create this entity manager using the EntityManagerFactory's method createEntityManager. You have to use the javax.persistence.Persistence class to bootstrap an EntityManagerFactory instance, as this example shows:

Notice that you need to explicitly close the entity manager and the factory.

In the Java EE environment, you can use the application-managed entity managers as well. You would create it using the @PersistenceUnit annotation to declare a reference to the EntityManagerFactory for a persistence unit, as the following example shows:

@PersistenceUnit
EntityManagerFactory emf;

Note: You can only use the @PersistenceContext annotation injection on session beans, servlets and JSP.

For more information and examples, see the following sections of the JPA Specification:

You define the transaction type for a persistence unit and configure it using the persistence.xml file (see persistence.xml File).

For more information, see Section 5.5 "Controlling Transactions" of the JPA Specification.

JTA Transaction Management

JTA transactions are the transactions of the Java EE server.

As section 5.5.1 "JTA Entity Managers" of the JPA Specification defines, "An entity manager whose transactions are controlled through JTA is a JTA entity manager. A JTA entity manager participates in the current JTA transaction, which is begun and committed external to the entity manager and propagated to the underlying resource manager."

Resource-Local Transactions

Resource-local transactions are the native transactions of the JDBC drivers that are referenced by a persistence unit. Your application explicitly controls these transactions. Your application interacts with the resource-local transactions by acquiring an implementation of the EntityTransaction interface from the entity manager.

For more information and examples, see the following sections of the JPA Specification.

Introduction to EclipseLink JPA

As a specification, JPA needs to be implemented by vendors or open source projects.

EclipseLink provides a complete, EJB 3.0-compliant JPA implementation. It provides complete compliance for all of the mandatory features, many of the optional features, and some additional features. The additional nonmandatory functionality includes the following:

object-level cache;

distributed cache coordination;

extensive performance tuning options;

enhanced Oracle Database support;

advanced mappings;

optimistic and pessimistic locking options;

extended annotations and query hints.

EclipseLink offers support for deployment within an EJB 3.0 container. This includes Web containers and other non-EJB 3.0 Java EE containers. For more information, see Deploying an EclipseLink JPA Application.

Through its pluggable persistence capabilities EclipseLink can function as the persistence provider in a compliant EJB 3.0 container.

Using Metadata Annotations

An annotation is a simple, expressive means of decorating Java source code with metadata that is compiled into the corresponding Java class files for interpretation at run time by a JPA persistence provider to manage persistent behavior.

You can use annotations to configure the persistent behavior of your entities. For example, to designate a Java class as a JPA entity, use the @Entity annotation (see Section 8.1 "Entity" of the JPA Specification) as follows:

@Entitypublicclass Employee implementsSerializable{
...
}

You can apply annotations at three different levels: at the class, method, and field levels.

The root element of the mapping file is called entity-mappings. All object relational XML metadata is contained within this element. The subelements of entity-mappings can be categorized into four main scoping and functional groups: persistence unit defaults, mapping file defaults, queries and generators, and managed classes and mappings. There is also a special setting that determines whether annotations should be considered in the metadata for the persistence unit.

For more information and examples, see Section 10.1 "XML Overriding Rules" of the JPA Specification.

Overriding and Merging XML

You can use EclipseLink’s native metadata xml file, EclipseLink-ORM.XML, to override mappings defined in JPA’s configuration file orm.xml and provide EclipseLink with extended ORM features. For more information on JPA extensions for mapping, see Using EclipseLink JPA Extensions.

The EclipseLink-ORM.XML file defines the object-relational mapping metadata for EclipseLink. It is built from the existing orm.xml file which makes it more intuitive, requires minimum configuration, and easy to override. For more information, see Section 10.1 "XML Overriding Rules" of the JPA Specification.

To override orm.xml file's mapping, you must define the META-INF/eclipselink-orm.xml file in the project. When both orm.xml and eclipselink-orm.xml are specified, the contents of eclipselink-orm.xml override orm.xml and any other JPA mapping file specified in the persistence unit. If there are overlapping specifications in multiple ORM files, the files are merged if they are no conflicting entities.

Note: The order of files defined in persistence.xml does not define the order of their processing. The files are processed, merged and overidden as required. For more information, see Overriding and Merging Examples.

The EclipseLink-ORM.XML file can be referenced for inclusion in a persistence unit’s metadata through any of the following files or methods:

File/Method

Description

META-INF/eclipselink-orm.xml

Provides mapping overriding capabilities.

META-INF/orm.xml

The default ORM file provided with JPA.

Referenced as persistence unit mapping file in persistence.xml

Does not provide mapping overriding capability, but can be used for merging mapping files.

Overriding and Merging Examples

Example 1

META-INF/orm.xml - defines Entity A with the mappings b and c.

META-INF/eclipselink-orm.xml - defines Entity A with the mappings for c and d.

If an entity-listeners exists, then the EclipseLink-ORM.XML's entity-listeners will be merged with the list of all entity-listeners from the persistence unit.

Entity Mappings

Entities, embeddables and mapped superclasses are defined within entity-mappings. EclipseLink-ORM.XML's entities, embeddables and mapped superclasses are added to the persistence unit. The following table describes the top-level elements of the entity-mappings sections:

entity-mappings/

Rule

Description

package

None

The package element specifies the package of the classes listed within the subelements and attributes of the same mapping file only. It is only applicable to those entities that are fully defined within the EclipseLink-ORM.XML file, else its usage remains local and is same as described in the JPA specification.

catalog

None

The catalog element applies only to the subelements and attributes listed within the EclipseLink-ORM.XML file that are not an extension to another mapping file. Otherwise, the use of the catalog element within the EclipseLink-ORM.XML file remains local and is same as described in the JPA specification.

schema

None

The schema element applies only to the subelements and attributes listed within the EclipseLink-ORM.XML file that are not an extension to another mapping file. Otherwise, the use of the schema element within the EclipseLink-ORM.XML file remains local and is same as described in the JPA specification.

access

None

The access element applies only to the subelements and attributes listed within the EclipseLink-ORM.XML file that are not an extension to another mapping file. Otherwise, the use of the access element within the EclipseLink-ORM.XML file remains local and is same as described in the JPA specification.

sequence-generator

Full override

A sequence-generator is unique by name. The sequence-generator defined in the EclipseLink-ORM.XML will override a sequence-generator of the same name defined in another mapping file. Outside of the overriding case, an exception is thrown if two or more sequence-generators with the same name are defined in one or across multiple mapping files.

table-generator

Full override

A table-generator is unique by name. The table-generator defined in the EclipseLink-ORM.XML will override a table-generator of the same name defined in another mapping file. Outside of the overriding case, an exception is thrown if two or more table-generators with the same name are defined in one or across multiple mapping files.

named-query

Full override

A named-query is unique by name. The named-query defined in the EclipseLink-ORM.XML will override a named-query of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more named-querys with the same name are defined in one or across multiple mapping file.

named-native-query

Full override

A named-native-query is unique by name. The named-native-query defined in the EclipseLink-ORM.XML will override a named-native-query of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more named-native-querys with the same name are defined in one or across multiple mapping files.

sql-result-set-mapping

Full override

A sql-result-set-mapping is unique by name. The sql-result-set-mapping defined in the EclipseLink-ORM.XML will override a sql-result-set-mapping of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more sql-result-set-mapping entities with the same name are defined in one or across multiple mapping files.

Mapped Superclass

A mapped-superclass can be defined completely, or with specific elements to provide extensions to a mapped-superclass from another mapping file. The following table lists individual override and merging rules:

entity-mappings/mapped-superclass

Rule

Description

id-class

Full override

If an id-class setting exists, then the EclipseLink-ORM.XML's id-class setting overrides the existing setting, or creates a new id-class setting.

exclude-default-listeners

Full override

If an exclude-default-listeners setting exists, then the EclipseLink-ORM.XML's exclude-default-listeners setting will be applied. If the exclude-default-listeners setting is not specified, it will not override an existing setting, that is essentially turning it off.

exclude-superclass-listeners

Full override

If an exclude-superclass-listeners setting exists, then the EclipseLink-ORM.XML's exclude-superclass-listeners setting will be applied. If exclude-superclass-listeners setting is not specified, it will not override an existing setting, that is essentially turning it off.

entity-listeners

Merge and full override

If an entity-listeners setting exists, then the EclipseLink-ORM.XML's entity-listeners setting will override and merge with an existing setting, or creates a new entity-listeners setting all together. Note: An entity listener override must be complete. All lifecycle methods of that listener must be specified and no merging of individual lifecycle methods of an entity listener is allowed. The class name of the listener is the key to identify the override.

pre-persist

Full override

If a pre-persist setting exists, then the EclipseLink-ORM.XML's pre-persist setting overrides the existing setting, or creates a new pre-persist setting.

post-persist

Full override

If a post-persist setting exists, then the EclipseLink-ORM.XML's post-persist setting overrides the existing setting, or creates a new post-persist setting.

pre-remove

Full override

If a pre-remove setting exists, then the EclipseLink-ORM.XML's pre-remove setting overrides the existing setting, or creates a new pre-remove setting.

post-remove

Full override

If a post-remove setting exists, then the EclipseLink-ORM.XML's post-remove setting overrides the existing setting, or creates a new post-remove setting.

pre-update

Full override

If a pre-update setting exists, then the EclipseLink-ORM.XML's pre-update setting overrides the existing setting, or creates a new pre-update setting.

post-update

Full override

If a post-update setting exists, then the EclipseLink-ORM.XML's post-update setting overrides the existing setting, or creates a new post-update setting.

post-load

Full override

If a post-load setting exists, then the EclipseLink-ORM.XML's post-load setting overrides the existing setting, or creates a new post-load setting.

If an access setting exists, then the EclipseLink-ORM.XML's access setting overrides the existing setting, or creates a new access setting. It also overrides the default class setting.

metadata-complete

Full override

If a metadata-complete setting exists, then the EclipseLink-ORM.XML's metadata-complete setting will be applied. If metadata-complete setting is not specified, it will not override an existing setting, that is essentially turning it off.

Entity override and merging rules

An entity can be defined completely, or with specific elements to provide extensions to an entity from another mapping file. The following table lists individual override and merging rules:

entity-mappings/entity

Rule

Comments

table

Full override

The table definition overrides any other table setting (with the same name) for this entity. There is no merging of individual table values.

secondary-table

Full override

The secondary-table definition overrides another secondary-table setting (with the same name) for this entity. There is no merging of individual secondary-table(s) values.

primary-key-join-column

Full override

The primary-key-join-column(s) definition overrides any other primary-key-join-column(s) setting for this entity. There is no merging of the primary-key-join-column(s). The specification is assumed to be complete and these primary-key-join-columns are the source of truth.

id-class

Full override

If an id-class setting exists, then the EclipseLink-ORM.XML's id-class setting overrides the existing setting, or creates a new id-class setting.

inheritance

Full override

If an inheritance setting exists, then the EclipseLink-ORM.XML's inheritance setting overrides the existing setting, or creates a new inheritance setting.

discriminator-value

Full override

If a discriminator-value setting exists, then the EclipseLink-ORM.XML's discriminator-value setting overrides the existing setting, or creates a new discriminator-value setting.

discriminator-column

Full override

If a discriminator-column setting exists, then the EclipseLink-ORM.XML's discriminator-column setting overrides the existing setting, or creates a new discriminator-column setting.

sequence-generator

Full override

A sequence-generator is unique by name. The sequence-generator defined in EclipseLink-ORM.XML overrides sequence-generator of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more sequence-generators with the same name are defined in one or across multiple mapping files.

table-generator

Full override

A table-generator is unique by name. The table-generator defined in EclipseLink-ORM.XML overrides table-generator of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more table-generators with the same name are defined in one or across multiple mapping files.

named-query

Merge and full override

A named-query is unique by name. The named-query defined in EclipseLink-ORM.XML overrides named-query of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more named-query elements with the same name are defined in one or across multiple mapping files.

named-native-query

Merge and full override

A named-native-query is unique by name. The named-native-query defined in EclipseLink-ORM.XML overrides named-native-query of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more named-native-query elements with the same name are defined in one or across multiple mapping files.

sql-result-set-mapping

Merge and full override

A sql-result-set-mapping is unique by name. The sql-result-set-mapping defined in EclipseLink-ORM.XML overrides sql-result-set-mapping of the same name defined in other mapping files. Outside of the overriding case, an exception is thrown if two or more sql-result-set-mapping elements with the same name are defined in one or across multiple mapping files.

exclude-default-listeners

Full override

If an exclude-default-listeners setting exists, then the EclipseLink-ORM.XML's exclude-default-listeners setting will be applied. If an exclude-default-listeners setting is not specified, it will not override an existing setting, that is essentially turning it off.

exclude-superclass-listeners

Full override

If an exclude-superclass-listeners setting exists, then the EclipseLink-ORM.XML's exclude-superclass-listeners setting will be applied. If an exclude-superclass-listeners setting is not specified, it will not override an existing setting, that is essentially turning it off.

entity-listeners

Full override

If an entity-listeners setting exists, then the EclipseLink-ORM.XML's entity-listeners setting will override and merge with an existing setting, or creates a new entity-listeners setting all together. Note: An entity listener override must be complete. All lifecycle methods of that listener must be specified and no merging of individual lifecycle methods of an entity listener is allowed. The class name of the listener is the key to identify the override.

pre-persist

Full override

If a pre-persist setting exists, then the EclipseLink-ORM.XML's pre-persist setting overrides the existing setting, or creates a new pre-persist setting.

post-persist

Full override

If a post-persist setting exists, then the EclipseLink-ORM.XML's post-persist setting overrides the existing setting, or creates a new post-persist setting.

pre-remove

Full override

If a pre-remove setting exists, then the EclipseLink-ORM.XML's pre-remove setting overrides the existing setting, or creates a new pre-remove setting.

post-remove

Full override

If a post-remove setting exists, then the EclipseLink-ORM.XML's post-remove setting overrides the existing setting, or creates a new post-remove setting.

pre-update

Full override

If a pre-update setting exists, then the EclipseLink-ORM.XML's pre-update setting overrides the existing setting, or creates a new pre-update setting.

post-update

Full override

If a post-update setting exists, then the EclipseLink-ORM.XML's post-update setting overrides the existing setting, or creates a new post-update setting.

post-load

Full override

If a post-load setting exists, then the EclipseLink-ORM.XML's post-load setting overrides the existing setting, or creates a new post-load setting.

If an association-override setting exists, then the EclipseLink-ORM.XML's association-override setting overrides the existing setting, or creates a new association-override setting.

name

Full override

If a name setting exists, then the EclipseLink-ORM.XML's name setting overrides the existing setting, or creates a new name setting.

class

None

access

Full override

If an access setting exists, then the EclipseLink-ORM.XML's access setting overrides the existing setting, or creates a new access setting. It also overrides the default class setting.

metadata-complete

Full override

If a metadata-complete setting exists, then the EclipseLink-ORM.XML's metadata-complete setting will be applied. If a metadata-complete setting is not specified, it will not override an existing setting, that is essentially turning it off.

Embeddable

An embeddable can be defined wholely or may be defined so as to provide extensions to an embeddeable from another mapping file. Therefore, we will allow the merging of that classes metadata. The individual override rules for that metadata is tabled below.

entity-mappings/embeddable

Rule

Description

attributes

Override and merge

If the attribute settings (id, embedded-id, basic, version, many-to-one, one-to-many, one-to-one, many-to-many, embedded, transient) exist at the mapping level, then the EclipseLink-ORM.XML's attributes merges or overrides the existing settings, or creates new attributes.

class

None

access

Full override

If an access setting exists, then the EclipseLink-ORM.XML's access setting overrides the existing setting, or creates a new access setting. It also overrides the default class setting.

metadata-complete

Full override

If a metadata-complete setting exists, then the EclipseLink-ORM.XML's metadata-complete setting will be applied. If a metadata-complete setting is not specified, it will not override an existing setting, that is essentially turning it off.

Defaulting Properties

Each annotation has a default value (consult the JPA specification for defaults). A persistence engine defines defaults that apply to the majority of applications. You only need to supply values when you want to override the default value. Therefore, having to supply a configuration value is not a requirement, but the exception to the rule. This is known as configuration by exception.

Note: You should be familiar with the defaults to be able to change the behavior when necessary.

Configuring an Entity

You can configure your entity's identity, as well as the locking technique and sequence generation option for your entity.

Configuring an Entity Identity

Every entity must have a persistent identity, which is an equivalent of a primary key in a database table that stores the entity state.

By default, EclipseLink persistence provider assumes that each entity has at least one field or property that serves as a primary key.

You can generate and/or configure the identity of your entities by using the following annotations:

Note: The last option in the preceding list – @Id and @IdClass combination – is applicable to composite primary key configuration.

The @Id annotation does not have attributes.

By default, EclipseLink persistence provider chooses the most appropriate primary key generator (see @GeneratedValue) and is responsible for managing primary key values: you do not need to take any further action if you are satisfied with the persistence provider's default key generation mechanism.

This example shows how to use this annotation to designate the persistent field empID as the primary key of the Employee table.

For more information and examples, see Section 9.1.8 "Id Annotation" of the JPA Specification.

@IdClass

Use the @IdClass annotation to specify a composite primary key class (usually made up of two or more primitive, JDK object types or Entity types) for an entity or MappedSuperclass.

Note: Composite primary keys typically arise during mapping from legacy databases when the database key is comprised of several columns.

A composite primary key class has the following characteristics:

It is a POJO class.

It is a public class with a public no-argument constructor.

If you use property-based access, the properties of the primary key class are public or protected.

It is serializable.

It defines equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.

Its fields or properties must correspond in type and name to the entity primary key fields or properties annotated with @Id.

Alternatively, you can make the composite primary key class an embedded class owned by the entity (see @EmbeddedId).

The @IdClass annotation has a required attribute value that you set to the class to specify this class as a composite primary key class (see @AttributeOverride).

The Nonembedded Composite Primary Key Class example shows a nonembedded composite primary key class. In this class, fields empName and birthDay must correspond in name and type to properties in the entity class. The Usage of @IdClass Annotation example shows how to configure an entity with this nonembedded composite primary key class using the @IdClass annotation. Because entity class fields empName and birthDay are used in the primary key, you must also annotate them using the @Id annotation (see @Id).

For more information and examples, see Section 9.1.15 "IdClass Annotation" of the JPA Specification.

@EmbeddedId

Use the @EmbeddedId annotation to specify an embeddable composite primary key class (usually made up of two or more primitive or JDK object types) owned by the entity.

Note: Composite primary keys typically arise during mapping from legacy databases when the database key is comprised of several columns.

A composite primary key class has the following characteristics:

It is a POJO class.

It is a public class with a public no-argument constructor.

If you use property-based access, the properties of the primary key class are public or protected.

It is serializable.

It defines equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.

Alternatively, you can make the composite primary key class a nonembedded class (see @IdClass).

The @EmbeddedId annotation does not have attributes.

This example shows a typical composite primary key class annotated with @Embeddable. The Usage of @EmbeddedId Annotation example shows how to configure an entity with this embeddable composite primary key class using the @EmbeddedId annotation.

@GeneratedValue

override the type of identity value generation selected by the persistence provider for your database if you feel another generator type is more appropriate for your database or application;

override the primary key generator name selected by the persistence provider if this name is awkward, a reserved word, incompatible with a preexisting data model, or invalid as a primary key generator name in your database.

The @GeneratedValue annotation has the following attributes:

generator – The default value of this attribute is the name that EclipseLink persistence provider assigns to the primary key generator it selects.If the generator name is awkward, a reserved word, incompatible with a preexisting data model, or invalid as a primary key generator name in your database, set the value of this attribute to the String generator name you want to use.

You are not required to specify the value of this attribute.

strategy – By default, EclipseLink persistence provider chooses the type of primary key generator that is most appropriate for the underlying database.If you feel that another generator type is more appropriate for your database or application, set the value of this attribute to one of the following enumerated values of the GenerationType enumerated type:

AUTO (default) – specify that EclipseLink persistence provider should choose a primary key generator that is most appropriate for the underlying database.

Note: By default, EclipseLink chooses the TABLE strategy using a table named SEQ_GEN_TABLE, with SEQ_NAME and SEQ_COUNT columns, with allocationSize of 50 and pkColumnValue of SEQ_GEN. The default SEQUENCE used is database sequence SEQ_GEN_SEQUENCE with allocationSize of 50. Note that the database sequence increment must match the allocation size.

IDENTITY – specify that EclipseLink persistence provider use a database identity column. Setting this value will indicate to the persistence provider that it must reread the inserted row from the table after an insert has occurred. This will allow it to obtain the newly generated identifier from the database and put it into the in-memory entity that was just persisted. The identity must be defined as part of the database schema for the primary key column. Identity generation may not be shared across multiple entity types.

Note: There is a difference between using IDENTITY and other id generation strategies: the identifier will not be accessible until after the insert has occurred – it is the action of inserting that caused the identifier generation. Due to the fact that insertion of entities is most often deferred until the commit time, the identifier would not be available until after the transaction has been committed.

Note: We do not recommend using the IDENTITY strategy for it does not support preallocation.

You are not required to specify the value of the strategy attribute. This example shows how to use automatic id generation. This will cause EclipseLink persistence provider to create an identifier value and insert it into the id field of each Employee entity that gets persisted.

Caution: Be careful when using the automatic id generation: the persistence provider has to pick its own strategy to store the identifiers, but it needs to have a persistent resource, such as a table or a sequence, to do so. The persistence provider cannot always rely upon the database connection that it obtains from the server to have permissions to create a table in the database. This is usually a privileged operation that is often restricted to the DBA. There will need to be a creation phase or schema generation to cause the resource to be created before the AUTO strategy can function.

For more information and examples, see Section 9.1.9 "GeneratedValue Annotation" of the JPA Specification.

Configuring Sequence Generation

Many databases support an internal mechanism for id generation called sequences. You can use a database sequence to generate identifiers when the underlying database supports them.

@SequenceGenerator

If you use the @GeneratedValue annotation to specify a primary key generator of type SEQUENCE, then you can use the @SequenceGenerator annotation to fine-tune this primary key generator to do the following:

The value of this attribute must match the increment size on the database sequence object. If this allocation size does not match your application requirements or database performance parameters, set this attribute to the int value you want.

You are not required to specify the value of the allocationSize attribute.

initialValue – By default, EclipseLink persistence provider starts all primary key values from 0.If this does not match an existing data model, set this attribute to the int value you want.

You are not required to specify the value of the initialValue attribute.

sequenceName – By default, EclipseLink persistence provider assigns a sequence name of its own creation.

The sequenceName defaults to the name of the SequenceGenerator. If you prefer to use an existing or predefined sequence, set sequenceName to the String name you want.

You are not required to specify the value of the sequenceName attribute.

This example shows how to use this annotation to specify the allocation size for the SEQUENCE primary key generator named Cust_Seq.

change the initial value to match an existing data model (for example, if you are building on an existing data set, for which a range of primary key values has already been assigned or reserved);

configure the primary key generator's table with a specific catalog or schema;

configure a unique constraint on one or more columns of the primary key generator's table;

The @TableGenerator annotation has the following attributes:

name – The name of the generator must match the name of a GeneratedValue with its strategy attribute set to TABLE. The scope of the generator name is global to the persistence unit (across all generator types).

You are required to specify the value of this attribute.

allocationSize – By default, EclipseLink persistence provider uses an allocation size of 50.If this allocation size does not match your application requirements or database performance parameters, set this attribute to the int value you want.

You are not required to specify the value of the allocationSize attribute.

catalog – By default, EclipseLink persistence provider uses whatever the default catalog is for your database.If the default catalog is inappropriate for your application, set the value of this attribute to the String catalog name to use.

You are not required to specify the value of the catalog attribute.

initialValue – By default, EclipseLink persistence provider starts all primary key values from 0.If this does not match an existing data model, set this attribute to the int value you want.

You are not required to specify the value of the initialValue attribute.

pkColumnName – By default, EclipseLink persistence provider supplies a name for the primary key column in the generator table: "SEQ_NAME".If this name is inappropriate for your application, set the value of this attribute to the String name you want.

You are not required to specify the value of the pkColumnName attribute.

pkColumnValue – By default, EclipseLink persistence provider supplies a suitable primary key value for the primary key column in the generator table: TableGenereator.name.If this value is inappropriate for your application, set the value of this attribute to the String value you want.

You are not required to specify the value of the pkColumnValue attribute.

schema – By default, EclipseLink persistence provider uses whatever the default schema is for your database.If this value is inappropriate for your application, set the value of this attribute to the String schema name you choose.

You are not required to specify the value of the schema attribute.

table – By default, EclipseLink persistence provider supplies a suitable name for the table that stores the generated id values: "SEQUENCE".If this value is inappropriate for your application, set the value of this attribute to the String table name you want.

You are not required to specify the value of the table attribute.

uniqueConstraints – By default, EclipseLink persistence provider assumes that none of the columns in the primary key generator table have unique constraints.If unique constraints do apply to one or more columns in this table, set the value of this attribute to an array of one or more UniqueConstraint instances. For more information, see Section 9.1.4 "UniqueConstraint Annotation" of the JPA Specification.

You are not required to specify the value of the uniqueConstraints attribute.

valueColumnName – By default, EclipseLink persistence provider supplies a suitable name for the column that stores the generated id values: "SEQ_COUNT".If the default column name is inappropriate for your application, set the value of this attribute to the String column name you want.

You are not required to specify the value of the valueColumnName attribute.

The Usage of @TableGenerator example shows how to use this annotation to specify the allocation size for the TABLE primary key generator named Emp_Gen.

Every table that you use for id generation should have two columns – if there are more columns, only two will be used. The first column is of a string type and is used to identify the particular generator sequence. It is the primary key for all of the generators in the table. The name of this column is specified by the pkColumnName attribute. The second column is of an integer type and stores the actual id sequence that is being generated. The value stored in this column is the last identifier that was allocated in the sequence. The name of this column is specified by the valueColumnName attribute.

Each defined generator represents a row in the table. The name of the generator becomes the value stored in the pkColumnName column for that row and is used by EclipseLink persistence provider to look up the generator to obtain its last allocated value.

For more information and examples, see Section 9.1.38 "TableGenerator Annotation" of the JPA Specification.

Configuring Locking

You have the choice between optimistic and pessimistic locking. We recommend using EclipseLink optimistic locking. For more information, see Locking.

By default, EclipseLink persistence provider assumes that the application is responsible for data consistency.

Use the @Version annotation to enable the JPA-managed optimistic locking by specifying the version field or property of an entity class that serves as its optimistic lock value (recommended).

When choosing a version field or property, ensure that the following is true:

there is only one version field or property per entity;

you choose a property or field persisted to the primary table (see Section 9.1.1 "Table Annotation" of the JPA Specification);

your application does not modify the version property or field.

Note: The field or property type must either be a numeric type (such as Number, long, int, BigDecimal, and so on), or a java.sql.Timestamp. We recommend using a numeric type.

The @Version annotation does not have attributes.

The Usage of @Version Annotation example shows how to use this annotation to specify property getVersionNum as the optimistic lock value. In this example, the column name for this property is set to OPTLOCK (see Section 9.1.5 "Column Annotation" of the JPA Specification) instead of the default column name for the property.

fetch – By default, EclipseLink persistence provider uses a fetch type of javax.persitence.FetchType.EAGER: data must be eagerly fetched.If the default is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).You are not required to specify the value of this attribute.For more information, see What You May Need to Know About EclipseLink JPA Lazy Loading.

optional – By default, EclipseLink persistence provider assumes that the value of all (nonprimitive) fields and properties may be null.If the default is inappropriate for your application, set this the value of this attribute to false.

You are not required to specify the value of this attribute.

This example shows how to use this annotation to specify a fetch type of LAZY for a basic mapping.

@Enumerated

Use the @Enumerated annotation to specify whether EclipseLink persistence provider should persist ordinal or String values of enumerated constants if the String value suits your application requirements, or to match an existing database schema:

value – By default, EclipseLink persistence provider assumes that for a property or field mapped to an enumerated constant, the ordinal value should be persisted. In the Usage of the @Enumerated Annotation example, the ordinal value of EmployeeStatus is written to the database when Employee is persisted.If you want the String value of the enumerated constant persisted, set value to EnumType.STRING.

You are not required to specify the value of this attribute.

Given the enumerated constants in the Enumerated Constants example, the Usage of the @Enumerated Annotation example shows how to use the @Enumerated annotation to specify that the String value of SalaryRate should be written to the database when Employee is persisted. By default, the ordinal value of EmployeeStatus is written to the database.

For more information and examples, see Section 9.1.20 "Temporal Annotation" of the JPA Specification.

@Transient

By default, EclipseLink persistence provider assumes that all the fields of an entity are persistent.

Use the @Transient annotation to specify a field or property of an entity that is not persistent (for example, a field or property that is used at run time, but that is not part of the entity's state).

EclipseLink persistence provider will not persist (or create database schema) for a property or field annotated with @Transient.

The Usage of the @Transient Annotation example shows how to use the @Transient annotation to specify Employee field currentSession as not persistent. EclipseLink persistence provider will not persist this field.

At end of relationships section should link to the EclipseLink relationships mappings section and state that additional advanced mapping and mapping options are available through EclipseLink's descriptor and mapping API through using a DescriptorCustomizer.

@OneToOne

By default, JPA automatically defines a OneToOne mapping for a single-valued association to another entity that has one-to-one multiplicity and infers the associated target entity from the type of the object being referenced.

configure the associated target entity, if it cannot be inferred from the type of the object being referenced;

configure the operations that must be cascaded to the target of the association (for example, if the owning entity is removed, ensure that the target of the association is also removed).

The @OneToOne annotation has the following attributes:

cascade – By default, JPA does not cascade any persistence operations to the target of the association. Thus, the default value of this attribute is an empty javax.persitence.CascadeType array.If you want some or all persistence operations cascaded to the target of the association, set the value of this attribute to one or more CascadeType instances, including the following:

ALL – Any persistence operation performed on the owning entity is cascaded to the target of the association.

MERGE – If the owning entity is merged, the merge is cascaded to the target of the association.

PERSIST – If the owning entity is persisted, the persist is cascaded target of the association.

REFRESH – If the owning entity is refreshed, the refresh is cascaded target of the association.

REMOVE – If the owning entity is removed, the target of the association is also removed.

You are not required to provide value for this attribute.

fetch – By default, EclipseLink persistence provider uses a fetch type of javax.persitence.FetchType.EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.If the default is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible). We recommend using the FetchType.LAZY on all relationships.You are not required to provide value for this attribute.For more information, see What You May Need to Know About EclipseLink JPA Lazy Loading.

mappedBy – By default, EclipseLink persistence provider infers the associated target entity from the type of the object being referenced.Use the mappedBy attribute if the relationship is bidirectional and the target entity has an inverse one-to-one relationship that has already been mapped. You can only use mappedBy on the side of the relationship that does not define the foreign key in its table. This is the only way in JPA to define a target foreign key relationship. For example, if the foreign key for the one-to-one is in the target entity's table, you must define the one-to-one mapping on both sides of the relationship and use the mappedBy on the target foreign key side. For more information on target foreign keys, see One-to-One Mapping.

You are not required to specify the value of this attribute.

optional – By default, EclipseLink persistence provider assumes that the value of all (nonprimitive) fields and properties may be null.

The default value of this attribute is true.If the default is inappropriate for your application, set value of this attribute to false.

You are not required to specify the value of this attribute.

targetEntity – By default, EclipseLink persistence provider infers the associated target entity from the type of the object being referenced.If the persistence provider cannot infer the type of the target entity, then set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.

Note: You have to provide a @JoinColumn (see Section 9.1.6 "JoinColumn Annotation" of the JPA Specification) for a @OneToOne defining the foreign key. Otherwise, the foreign key will be assumed to be the <source-field-name>_ <target-primary-key-column> or <source-property-name>_ <target-primary-key-column>.

Use either a @JoinColumn or a @JoinTable (see Section 9.1.25 "JoinTable Annotation" of the JPA Specification) with the mapping; if you do not specify any of them, EclipseLink will default to @JoinTable with the join table name format of <source-table-name>_<target-table-name> in uppercase characters, and with columns format of <source-entity-alias>_<source-primary-key-column>, <source-field-name>_ <target-primary-key-column> (or <source-property-name>_ <target-primary-key-column>) in uppercase characters.

configure the associated target entity, if it cannot be inferred from the type of the object being referenced;

configure the operations that must be cascaded to the target of the association (for example, if the owning entity is removed, ensure that the target of the association is also removed).

The @ManyToOne annotation has the following attributes:

cascade – By default, JPA does not cascade any persistence operations to the target of the association. Thus, the default value of this attribute is an empty javax.persistence.CascadeType array.If you want some or all persistence operations cascaded to the target of the association, set the value of this attribute to one or more CascadeType instances, including the following:

ALL – Any persistence operation performed on the owning entity is cascaded to the target of the association.

MERGE – If the owning entity is merged, the merge is cascaded to the target of the association.

PERSIST – If the owning entity is persisted, the persist is cascaded target of the association.

REFRESH – If the owning entity is refreshed, the refresh is cascaded target of the association.

REMOVE – If the owning entity is removed, the target of the association is also removed.

You are not required to provide value for this attribute.

fetch – By default, EclipseLink persistence provider uses a fetch type of javax.persitence.FetchType.EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.If the default is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).

optional – By default, EclipseLink persistence provider assumes that the value of all (nonprimitive) fields and properties may be null.

The default value of this attribute is true.If the default is inappropriate for your application, set value of this attribute to false.

You are not required to specify the value of this attribute.

targetEntity – By default, EclipseLink persistence provider infers the associated target entity from the type of the object being referenced.If the persistence provider cannot infer the type of the target entity, then set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.

You are not required to specify the value of this attribute.

This example shows how to use this annotation to configure a many-to-one mapping between Customer (the owned side) and Order (the owning side) using generics.

Note: You have to provide a @JoinColumn (see Section 9.1.6 "JoinColumn Annotation" of the JPA Specification) for a @ManyToOne defining the foreign key. Otherwise, the foreign key will be assumed to be the <source-field-name>_ <target-primary-key-column> or <source-property-name>_ <target-primary-key-column>.

Use either a @JoinColumn or a @JoinTable (see Section 9.1.25 "JoinTable Annotation" of the JPA Specification) with the mapping; if you do not specify any of them, EclipseLink will default to @JoinTable with the join table name format of <source-table-name>_<target-table-name> in uppercase characters, and with columns format of <source-entity-alias>_<source-primary-key-column>, <source-field-name>_ <target-primary-key-column> (or <source-property-name>_ <target-primary-key-column>) in uppercase characters.

For more information and examples, see Section 9.1.22 "ManyToOne Annotation" of the JPA Specification.

@OneToMany

By default, JPA automatically defines a OneToMany mapping for a many-valued association with one-to-many multiplicity.

Use the OneToMany annotation to do the following:

configure the fetch type to EAGER;

configure the associated target entity, because the Collection used is not defined using generics;

configure the operations that must be cascaded to the target of the association: for example, if the owning entity is removed, ensure that the target of the association is also removed;

configure the details of the join table used by the persistence provider for unidirectional one-to-many relationships (see Section 9.1.25 "JoinTable Annotation" of the JPA Specification).

The @OneToMany annotation has the following attributes:

cascade – By default, JPA does not cascade any persistence operations to the target of the association. Thus, the default value of this attribute is an empty javax.persitence.CascadeType array.If you want some or all persistence operations cascaded to the target of the association, set the value of this attribute to one or more CascadeType instances, including the following:

ALL – Any persistence operation performed on the owning entity is cascaded to the target of the association.

MERGE – If the owning entity is merged, the merge is cascaded to the target of the association.

PERSIST – If the owning entity is persisted, the persist is cascaded target of the association.

REFRESH – If the owning entity is refreshed, the refresh is cascaded target of the association.

REMOVE – If the owning entity is removed, the target of the association is also removed.

You are not required to provide value for this attribute.

fetch – By default, EclipseLink persistence provider uses a fetch type of javax.persitence.FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).If the default is inappropriate for your application or a particular persistent field, set fetch to FetchType.EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.

mappedBy – By default, if the relationship is unidirectional, EclipseLink persistence provider determines the field that owns the relationship.If the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship, as the Usage of @ManyToOne Annotation - Order Class with Generics example shows.

You are not required to specify the value of this attribute.

targetEntity – By default, if you are using a Collection defined using generics, then the persistence provider infers the associated target entity from the type of the object being referenced. Thus, the default is the parameterized type of the Collection when defined using generics.If your Collection does not use generics, then you must specify the entity class that is the target of the association: set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.

configure the associated target entity because the Collection used is not defined using generics;

configure the operations that must be cascaded to the target of the association (for example, if the owning entity is removed, ensure that the target of the association is also removed).

The @ManyToMany annotation has the following attributes:

cascade – By default, JPA does not cascade any persistence operations to the target of the association. Thus, the default value of this attribute is an empty javax.persitence.CascadeType array.If you want some or all persistence operations cascaded to the target of the association, set the value of this attribute to one or more CascadeType instances, including the following:

ALL – Any persistence operation performed on the owning entity is cascaded to the target of the association.

MERGE – If the owning entity is merged, the merge is cascaded to the target of the association.

PERSIST – If the owning entity is persisted, the persist is cascaded target of the association.

REFRESH – If the owning entity is refreshed, the refresh is cascaded target of the association.

REMOVE – If the owning entity is removed, the target of the association is also removed.

You are not required to provide value for this attribute.

fetch – By default, EclipseLink persistence provider uses a fetch type of javax.persitence.FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).If the default is inappropriate for your application or a particular persistent field, set fetch to FetchType.EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.

mappedBy – By default, if the relationship is unidirectional, EclipseLink persistence provider determines the field that owns the relationship.If the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship, as the Usage of @ManyToMany Annotation - Project Class with Generics example shows.

You are not required to specify the value of this attribute.

targetEntity – By default, if you are using a Collection defined using generics, then the persistence provider infers the associated target entity from the type of the object being referenced. Thus, the default is the parameterized type of the Collection when defined using generics.If your Collection does not use generics, then you must specify the entity class that is the target of the association: set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.

Note: Use a @JoinTable (see Section 9.1.25 "JoinTable Annotation" of the JPA Specification) annotation to define a many-to-many join table; if you do not specify this annotation, EclipseLink will default to @JoinTable with the join table name format of <source-table-name>_<target-table-name> in uppercase characters, and with columns format of <source-entity-alias>_<source-primary-key-column>, <source-field-name>_ <target-primary-key-column> (or <source-property-name>_ <target-primary-key-column>) in uppercase characters.

@MapKey

By default, EclipseLink persistence provider assumes that the primary key of the associated entity is the map key for associations of type java.util.Map. If the primary key is a noncomposite primary key annotated with the @Id annotation, an instance of this field or property's type is used as the map key.

Use the @MapKey annotation to specify the following:

some other field or property as the map key if the primary key of the associated entity is not appropriate for your application;

The field or property you specify must have a unique constraint (see Section 9.1.4 "UniqueConstraint Annotation" of the JPA Specification).

The @MapKey annotation has the following attributes:

name – By default, EclipseLink persistence provider uses the primary key of the associated entity as the Map key for a property or field mapped to a java.util.Map for noncomposite primary keys, or composite primary keys annotated with the @IdClass annotation (see @IdClass).If you want to use some other field or property as the map key, set name to the associated entity's String field or property name to use.

For more information and examples, see Section 9.1.27 "MapKey Annotation" of the JPA Specification.

@OrderBy

Use the @OrderBy annotation with @OneToMany and @ManyToMany to specify the following:

one or more other field or property names to order by;

different orders (ascending or descending) for each such field or property names.

The @OrderBy annotation has the following attributes:

value – By default, EclipseLink persistence provider retrieves the members of an association in ascending order by primary key of the associated entities.If you want to order by some other fields or properties and specify different, set value to a comma-separated list of the following elements: "property-or-field-name ASC|DESC" (see Example 1-65).

You are not required to provide value for this attribute.

This example shows how to use the @OrderBy annotation to specify that the Project method getEmployees should return a List of Employee in ascending order by Employee field lastname, and in descending order by Employee field seniority.

@Inheritance

By default, the EclipseLink persistence provider automatically manages the persistence of entities in an inheritance hierarchy.

Use the @Inheritance annotation to customize the persistence provider's inheritance hierarchy support to improve application performance or to match an existing data model.

The @Inheritance annotation has the following attributes:

strategy – By default, the EclipseLink persistence provider assumes that all the classes in a hierarchy are mapped to a single table differentiated by the discriminator value (see @DiscriminatorValue) in the table's discriminator column (see @DiscriminatorColumn): InheritanceType.SINGLE_TABLE.If this is not appropriate for your application or if you must match an existing data model, set strategy to the desired InheritanceType enumerated type:

SINGLE_TABLE – all the classes in a hierarchy are mapped to a single table. The table has a discriminator column (@DiscriminatorColumn) whose value (@DiscriminatorValue) identifies the specific subclass to which the instance that is represented by the row belongs.

Note: This option provides the best support for both polymorphic relationships between entities and queries that range over the class hierarchy. The disadvantages of this option include the need to make nullable columns that should be NOT NULL.

For more information, see Section 2.1.10.1 "Single Table per Class Hierarchy Strategy" of the JPA Specification.

TABLE_PER_CLASS – each class is mapped to a separate table. All properties of the class, including inherited properties, are mapped to columns of the table for the class.

Note: This option is available starting in EclipseLink Release 1.1. For earlier versions, you can instead either map each entity subclass independently, or use a @MappedSuperclass.

For more information, see Section 2.1.10.2 "Table per Concrete Class Strategy" of the JPA Specification.

JOINED – the root of the class hierarchy is represented by a single table and each subclass is represented by a separate table. Each subclass table contains only those fields that are specific to the subclass (not inherited from its superclass) and primary key columns that serve as foreign keys to the primary keys of the superclass table.For more information, see Section 2.1.10.3 "Joined Subclass Strategy" of the JPA Specification.

You are not required to specify the value of this attribute.

This example shows how to use this annotation to specify that all subclasses of Customer will use InheritanceType.JOINED. The subclass in the @Inheritance - Subclass Using JOINED example will be mapped to its own table that contains a column for each the persistent properties of ValuedCustomer and one foreign key column that contains the primary key to the Customer table.

@MappedSuperclass

By default, a EclipseLink persistence provider assumes that all the persistent fields of an entity are defined in that entity.

The @MappedSuperclass annotation lets you define mappings in a nonpersistent abstract superclass and enable their inheritance by the subclasses. You can use the @AttributeOverride and @AssociationOverride annotations to override the mapping information in these subclasses.

Use the @MappedSuperclass annotation to designate a superclass from which your entity class inherits persistent fields. This is a convenient pattern when multiple entity classes share common persistent fields or properties.

You can annotate this superclass' fields and properties with any of the direct and relationship mapping annotations (such as @Basic and @ManyToMany) as you would for an entity, but these mappings apply only to its subclasses since no table exists for the superclass itself. The inherited persistent fields or properties belong to the subclass' table.

The @MappedSuperclass annotation does not have any attributes.

This example shows how to use the @MappedSuperclass annotation to specify Employee as a mapped superclass. The Extending a Mapped Superclass example shows how to extend this superclass in an entity and how to use the @AttributeOverride annotation in the entity class to override configuration made in the superclass.

@DiscriminatorColumn

By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, EclipseLink persistence provider creates a discriminator column named DTYPE to differentiate classes in an inheritance hierarchy.

Use the @DiscriminatorColumn annotation to do the following:

specify a discriminator column name if the column name in your data model is not the default column name DTYPE;

specify a discriminator column length that is appropriate for your application or a preexisting data model;

fine-tune the characteristics of the discriminator column in your database.

The @DiscriminatorColumn annotation has the following attributes:

columnDefinition – By default, EclipseLink persistence provider creates a database table column with minimal SQL: empty String.If you want the column created with more specialized options, set the value of this attribute to the SQL fragment that you want JPA to use when generating the DDL for the column.

You are not required to specify the value of this attribute.

discriminatorType – By default, EclipseLink persistence provider assumes that the discriminator type is a String: DiscriminatorType.STRING.If you want to use a different type, set the value of this attribute to DiscriminatorType.CHAR or DiscriminatorType.INTEGER.

length – By default, EclipseLink persistence provider assumes that the discriminator column has a maximum length of 255 characters when used to hold a String value. Default value of this attribute is 31.If this column width is inappropriate for your application or database, set the length to the int value appropriate for your database column.

name – By default, EclipseLink persistence provider assumes that the discriminator column is named "DTYPE".

To specify an alternative column name, set name to the String column name you want.

You are not required to specify the value of this attribute.

The @DiscriminatorColumn and @DiscriminatorValue - Root Class example shows how to use this annotation to specify a discriminator column named DISC of type STRING and length 20. In this example, the @DiscriminatorValue for this class is specified as CUST. The subclass in the @DiscriminatorValue - Subclass example specifies its own @DiscriminatorValue of VIP. In both Customer and ValuedCustomer, the value for @DiscriminatorValue must be convertible to the type specified by @DiscriminatorColumn attribute discriminatorType and must conform to @DiscriminatorColumn attribute length.

@DiscriminatorValue

By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, EclipseLink persistence provider uses a @DiscriminatorColumn to differentiate classes in the inheritance hierarchy by entity name (see Section 8.1 "Entity" of the JPA Specification).

Use the @DiscriminatorValue annotation to specify the discriminator value used to differentiate an entity in this inheritance hierarchy:

if the entity name is inappropriate for this application;

to match an existing database schema;

The @DiscriminatorValue annotation has the following attributes:

value – Set value to the String equivalent of a discriminator value that conforms to the @DiscriminatorColumn attributes discriminatorType and length.

You are required to specify the value of this attribute.

The @DiscriminatorColumn and @DiscriminatorValue - Root Class example shows how to use this annotation to specify a discriminator column named DISC of type STRING and length 20. In this example, the @DiscriminatorValue for this class is specified as CUST. The subclass in the @DiscriminatorValue - Subclass example specifies its own @DiscriminatorValue of VIP. In both Customer and ValuedCustomer, the value for @DiscriminatorValue must be convertible to the type specified by @DiscriminatorColumn attribute discriminatorType and must conform to @DiscriminatorColumn attribute length.

Using Embedded Objects

An embedded object does not have its own persistent identity – it is dependent upon an entity for its identity. For more information, see Section 2.1.5 "Embeddable Classes" of the JPA Specification.

By default, EclipseLink persistence provider assumes that every entity is mapped to its own table. Use the following annotations to override this behavior for entities that are owned by other entities:

@Embeddable

Use the @Embeddable annotation to specify a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.

For more information, see Section 9.1.34 "Embeddable Annotation" of the JPA Specification.

@Embedded

Use the @Embedded annotation to specify a persistent field whose @Embeddable type can be stored as an intrinsic part of the owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the owning entity.

You can use the @Embedded annotation in conjunction with @Embeddable to model a strict ownership relationship so that if the owning object is removed, the owned object is also removed.

Embedded objects should not be mapped across more than one table.

By default, column definitions (see Section 9.1.5 "Column Annotation" of the JPA Specification) specified in the @Embeddable class apply to the @Embedded class. If you want to override these column definitions, use the @AttributeOverride annotation.

The @Embedded annotation does not have attributes.

The Usage of the @Embedded Annotation example shows how to use this annotation to specify that @Embeddable class EmploymentPeriod (see the Usage of the @Embeddable Annotation) example may be embedded in the entity class using the specified attribute overrides (@AttributeOverride). If you do not need attribute overrides, you can omit the @Embedded annotation entirely: EclipseLink persistence provider will infer that EmploymentPeriod is embedded from its @Embeddable annotation.

For more information, see Section 9.1.35 "Embedded Annotation" of the JPA Specification.

@AttributeOverride

By default, EclipseLink persistence provider automatically assumes that a subclass inherits both persistent properties and their basic mappings from the superclass.

Use the @AttributeOverride annotation to customize a basic mapping inherited from a @MappedSuperclass or @Embeddable to change the @Column (see Section 9.1.5 "Column Annotation" of the JPA Specification) associated with the field or property if the inherited column definition is incorrect for your entity (for example, if the inherited column name is incompatible with a preexisting data model, or invalid as a column name in your database).

If you have more than one @AttributeOverride change to make, you must use the @AttributeOverrides annotation.

For more information, see Section 9.1.11 "AttributeOverrides Annotation" of the JPA Specification.

@AssociationOverride

By default, EclipseLink persistence provider automatically assumes that a subclass inherits both persistent properties and their association mappings from the superclass.

Use the @AssociationOverride annotation to customize an @OneToOne or @ManyToOne mapping inherited from a @MappedSuperclass (see @MappedSuperclass) or @Embeddable to change the @JoinColumn (see Section 9.1.6 "JoinColumn Annotation" of the JPA Specification) associated with the field or property if the inherited column definition is incorrect for your entity (for example, if the inherited column name is incompatible with a preexisting data model, or invalid as a column name in your database).

To customize an association mapping to change its @Column (see Section 9.1.5 "Column Annotation" of the JPA Specification), use the @AttributeOverride annotation.

The @AssociationOverride annotation has the following attributes:

joinColumns – To specify the join columns that are being mapped to the persistent attribute, set the joinColumns to an array of JoinColumn instances (see Section 9.1.6 "JoinColumn Annotation" of the JPA Specification).

The mapping type will remain the same as is defined in the embeddable class or mapped superclass.

You are required to specify the value of this attribute.

name – The name of the property in the embedded object that is being mapped if property-based access is being used, or the name of the field if field-based access is used.

Pass properties to the createEntityManagerFactory method, as the following example demonstrates. One property should indicate that exclusive connection should be used for classes that use isolated cache. Other properties should indicate that one or more specific entities use an isolated cache,

In the preceding example, the EntityManager uses a proxy user "john" for writes and reads inside a transaction. Note that reads, which are performed outside of the transaction, are done through the main (non-proxied) connection.

If you created your EntityManager using injection, set the properties as follows:

If proxy authentication properties are set when active persistence context already exists (that may happen if setProperty/setProperties method is used) then they will be ignored until a new one is created. Calling clear method on the EntityManager forces creation of the new active persistence context.

How to Define Proxy Properties Using EntityManagerFactory

You can also define proxy properties using the EntityManagerFactory. If you choose to do so, note that all connections will use these properties, unless they are overridden in the EntityManager. Consider the following example:

Proxy Authentication and application servers

Oracle Proxy Authentication may have conflicts with application servers' connections that wrap the actual Oracle connection. On some application servers after the proxy session was closed the statements that used the proxy session were still kept in the statement cache - that resulted in exception on attempt to use a closed statement. To workaround set application server statement cache size to zero.

You can inject an entity manager factory using the @PersistenceUnit annotation, as the following example shows, or you can obtain it through JNDI lookup. You may choose to specify the unitName element to designate the persistence unit whose factory you are using.

Obtaining an Entity Manager Factory in Java SE Environment

In Java SE environment, use the javax.persistence.Persistence bootstrap class to get access to an entity manager factory. In your application, create an entity manager factory by calling the javax.persistence.Persistence class' createEntityManagerFactory method (see Section 7.2.1 "javax.persistence.Persistence Class" of the JPA Specification), as the following example shows:

How to Obtain an Entity Manager

All entity managers come from factories of type EntityManagerFactory. The configuration for an entity manager is bound to the EntityManagerFactory that created it, but it is defined separately as a persistence unit. A persistence unit dictates either implicitly or explicitly the settings and entity classes used by all entity managers obtained from the unique EntityManagerFactory instance bound to that persistence unit. There is, therefore, a one-to-one correspondence between a persistence unit and its concrete EntityManagerFactory.Persistence units are named to allow differentiation of one EntityManagerFactory from another. This gives the application control over which configuration or persistence unit is to be used for operating on a particular entity.

How you obtain the entity manager and its factory depends on the Java environment in which you are developing your application:

Obtaining an Entity Manager in Java EE Application Server Environment

In the Java EE environment, you can inject an entity manager using the @PersistenceContext annotation, as the following example shows, or you can obtain it through a direct JNDI lookup. You may choose to specify the unitName element of the @PersistenceContext annotation to designate the persistence unit whose factory the container is using (see Section 8.4.2 "PersistenceUnit Annotation" of the JPA Specification). You can also specify the type element to indicate whether a transaction-scoped (default) or extended persistence context is to be used (see Section 5.6 "Container-managed Persistence Contexts" of the JPA Specification).

What You May Need to Know About Entity Managers and Their Factories

An entity manager persists and manages specific types of objects, enables reading from and writing to a given database. You have to configure the entity manager to do so. You are also responsible for configuring the entity manager to be implemented by a particular persistence provider, such as EclipseLink. The provider supplies the backing implementation engine for the entire Java Persistence API, which includes an entity manager, a Query implementation, and SQL generation.

An entity manager implements the API enabling operations on entities. It is encapsulated almost entirely within a single interface called EntityManager. Until you use an entity manager to create, read, or write an entity, the entity is nothing more than a regular nonpersistent Java object.

For more information, see Chapter 5 "Entity Managers and Persistence Contexts" of the JPA Specification.

Each entity manager factory provides entity manager instances that are all configured in the same manner (for example, configured to connect to the same database or use the same initial settings as defined by the implementation).

How to Use a Persistence Context

Information pending

Using an Extended Persistence Context

Information pending

What You May Need to Know About Persistence Contexts and Persistence Units

When an entity manager (see What You May Need to Know About Entity Managers and Their Factories) obtains a reference to an entity (either by having it explicitly passed in or because it was read from the database) that object becomes managed by the entity manager. The set of managed entity instances within an entity manager at any given time is called this entity manager's persistence context. Only one Java instance with the same persistent identity may exist in a persistence context at any time. For example, if an Employee with a persistent identity (or id) of 158 exists in the persistence context, then no other object with its id set to 158 may exist within that same persistence context.

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. The entity instances and their life cycle are managed within the persistence context. The EntityManager interface defines the methods for interacting with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

For more information, see Section 5.1 "Persistence Contexts" of the JPA Specification.

Persistence Unit

The set of entities that a given EntityManager instance manages is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by your application, and which must be collocated in their mapping to a single database.

A persistence unit includes the following:

An entity manager factory and its entity managers, together with their configuration information.

The set of classes managed by the entity managers.

Mapping metadata (in the form of metadata annotations and/or XML metadata) that specifies the mapping of the classes to the database.

Querying for an Entity

How to Use the Entity Manager find Method

Information pending

What You May Need to Know About Querying with Java Persistence Query Language

You can use the Java Persistence query language (JP QL) to define queries over entities and their persistent state.

JP QL is an extension of EJB QL, and adds the following features:

Single and multiple value result types;

Aggregate functions with sorting and grouping clauses;

A more natural jon syntax, including support for both inner and outer joins;

Conditional expressions involving subqueries;

Update and delete queries for bulk data changes;

Result projection into nonpersistent classes.

JP QL supports the use of dynamic queries and the use of named parameters. You can use it to define queries over the persistent entities, as well as their persistent state and relationships

You may define queries in metadata annotations or the XML descriptor.

A JP QL statement may be either a select statement, an update statement, or a delete statement. All statement types may have parameters. Any statement may be constructed dynamically or may be statically defined in a metadata annotation or XML descriptor element.

This example demonstrates how to create a simple query that finds all orders using JP QL.

Simple Query to Find All Objects

SELECTORDERFROMORDERORDER

This example demonstrates how to create a simple query that finds all orders to ship to California using JP QL.

What You May Need to Know About Named and Dynamic Queries

Named queries are static and expressed in metadata. You can define named queries using JP QL or SQL, scoping their names to the persistence unit.

Note: The query name must be unique within the scope of the persistence unit.

These queries are efficient to execute as the persistence provider can translate JP QL to SQL once, when you application starts, as opposed to every time the query is executed. You define a named query using the @NamedQuery annotation (see Section 8.3.1 "NamedQuery Annotation" of the JPA Specification), which you may place on the class definition for any entity. The annotation defines the name of the query, as well as the query text, as this example shows:

Place your named query on the entity class that most directly corresponds to the query result. In the preceding example, that would be the Employee entity.

If you need to define more than one named query for a class, place them inside of a @NamedQueries annotation (see Section 8.3.1 "NamedQuery Annotation" of the JPA Specification) that accepts an array of @NamedQuery annotations, as this example shows:

Because the query string is defined in the annotation, your application cannot alter it at run time. If you need to specify additional criteria, you must do it using query parameters. This example shows how you can use the createNamedQuery method of the EntityManager to create a named query that requires a query parameter.

You may choose to define named queries in an XML mapping file (see Using XML) using the named-query element. A named-query element in the mapping file may also override an existing query of the same name that was defined as an annotation. A named-query element may appear as a subelement of entity-mapping or entity elements. Regardless of where you defined it, it will be keyed by its name in the persistence unit query namespace. You may provide query hints as hint subelements.

This example shows the definition a named query in an XML mapping file. This query uses eclipselink.cache-usage hint to bypass the cache.

Dynamic queries are strings. You generate these queries at run time by passing the JP QL query string to the createQuery method of the EntityManager. There are no restrictions on the query definition; all JP QL query types are supported, as well as the use of parameters.

You may consider using dynamic queries in your application, if there might be a need to specify complex criteria and the exact shape of the query cannot be known in advance. However, note that if your application issues many queries, the use of dynamic queries will have a negative impact on performance.

Using Detached Entities and Lazy Loading

What You May Need to Know About Persisting with JP QL

You may define queries in metadata annotations or the XML descriptor.

You can use update and delete queries to persist your changes with JP QL.

You can perform bulk update of entities with the UPDATE statement. This statement operates on a single entity type and sets one or more single-valued properties of the entity subject to the condition in the WHERE clause. Update queries provide an equivalent to the SQL UPDATE statement, but with JP QL conditional expressions.

This example demonstrates how to use an update query to give employees a raise. The WHERE clause contains the conditional expression.

Update Query

UPDATE Employee e
SET e.salary =60000WHERE e.salary =50000

You can perform bulk removal of entities with the DELETE statement. Delete queries provide an equivalent to the SQL DELETE statement, but with JP QL conditional expressions.

This example demonstrates how to use a delete query to remove all employees who are not assigned to a department. The WHERE clause contains the conditional expression.

Delete Query

DELETEFROM Employee e
WHERE e.department ISNULL

Note: Delete queries are polymorphic: any entity subclass instances that meet the criteria of the delete query will be deleted. However, delete queries do not honor cascade rules: no entities other than the type referenced in the query and its subclasses will be removed, even if the entity has relationships to other entities with cascade removes enabled.

The persistence context is not updated to reflect results of update and delete operations. If you use a transaction-scoped persistence context, you should either execute the bulk operation in a transaction all by itself, or be the first operation in the transaction (see Introduction to EclipseLink Transactions). That is because any entity actively managed by the persistence context will remain unaware of the actual changes occurring at the database level.

What You May Need to Know About Persisting Results of Named and Dynamic Queries

Expressions listed in the SELECT clause of a query determine the result type of the query. The following are some of the type that may result from JP QL queries:

Basic types: String, primitive types, JDBC types

Entity types

An array of Object instances

User-defined types created from a constructor-expressions

The collection or single result corresponds directly to the result type of the query.

The Query interface provides three different ways to execute a query, depending on whether or not the query returns results and how many results are expected. For queries that return values, you can call either the following methods:

getResultList–use this method if you expect the query to return more than one result. This method returns a collection (List) containing query results. If there are no results to return, this method returns an empty collection.

getSingleResult–use this method if you expect the query to return a single result. In case of unexpected results, such as there are no results to return or multiple results are available, this method throws an exception.

The active persistence context manages a returned entity instance. If that entity instance is modified and the persistence context is part of a transaction, then the changes will be persisted to the database.

Note: If you use a transaction-scoped entity manager outside of a transaction, then the executed query will return detached entity instances instead of managed entity instances. To make changes to these detached entities, you must merge them into a persistence context before synchronizing with the database.

You can reuse Query objects as often as you need so long as the same persistence context that you used to create the query is active. For transaction-scoped entity managers, this limits the lifetime of the Query object to the life of the transaction. Other entity manager types may reuse Query objects until you close or remove the entity manager.

How to Use Extensions for Query

Using Query Hints

What You May Need to Know About Query Hints

Query hints are the JPA extension point for vendor-specific query features. Hints are the only feature in the query API that are not a standard usage: a hint is a string name and object value.

You may associate your queries with hints by either setting them in the persistence unit metadata as part of the @NamedQuery annotation (see Section 8.3.1 "NamedQuery Annotation" of the JPA Specification), or by using the setHint method of the Query.

The Using Query Hints example shows how to use the eclipselink.cache-usage hint to indicate that the cache should not be checked when reading an Employee for the database.

Note: Unlike the refresh method of the EntityManager, the eclipselink.cache-usage hint will not cause the query result to override the current cached value.

Using the Expression API

Information pending

How to Configure Lazy Loading

By default, the EclipseLink persistence provider will use dynamic weaving to configure all applicable mappings with lazy loading (indirection).

For JPA entities or POJO classes that you configure for weaving, EclipseLink weaves value holder indirection for one-to-one mappings. If you want EclipseLink to weave change tracking and your application includes collection mappings (one-to-many and many-to-many), then you must configure all collection mappings to use transparent indirect container indirection only (you may not configure your collection mappings to use eager loading, nor value holder indirection).

How to Configure Change Tracking

By default, the EclipseLink persistence provider will use dynamic weaving to configure all applicable mappings with attribute level change tracking.

For JPA entities or POJO classes that you configure for weaving, EclipseLink weaves value holder indirection for one-to-one mappings. If you want EclipseLink to weave change tracking and your application includes collection mappings (one-to-many and many-to-many), then you must configure all collection mappings to use transparent indirect container indirection only (you may not configure your collection mappings to use eager loading, nor value holder indirection).

What You May Need to Know About Cascading Entity Manager Operations

Typically, you use cascading in parent-child relationships.

By default, every entity manager operation applies only to the entity that you supplied as an argument to the operation. The operation will not cascade to other entities that have a relationship with the entity under operation. For some operations, such as remove, this is usually the desired behavior. For other operations, such as persist, it is not: in most cases, if you have a new entity that has a relationship to another new entity, you would want to persist both entities together.

Using the cascade element of relationship annotations (see Mapping Relationships), you can define whether or not to cascade operations across relationships.

When listed as a part of the cascade element, you can identify the entity manager operations with the following constant values using the javax.persitence.CascadeType enumerated type:

PERSIST–corresponds to the entity manager persist operation;

REFRESH–corresponds to the entity manager refresh operation;

REMOVE–corresponds to the entity manager remove operation;

MERGE–corresponds to the entity manager merge operation;

ALL–indicates that all four operations should be cascaded.

Note: Cascade sessions are unidirectional: you must set them on both sides of a relationship if you plan for the same behavior for both situations.

Packaging and Deploying EclipseLink JPA Applications

Packaging an EclipseLink JPA Application

Packaging means assembling all parts of the application in a way that can be correctly interpreted and used by the infrastructure when the application is deployed into an application server or run in a stand-alone JVM.

Once you chose a packaging strategy, place the persistence.xml file in the META-INF directory of the archive of your choice.

In a Java EE environment, the most efficient way to package your application is to use a tool, such as JDeveloper or Eclipse. Using OC4J, it is possible to skip the packaging step and deploy from your working directories using expanded deployment.

To package your EclipseLink JPA application, you need to configure the persistence unit during the creation of the persistence.xml file. Define each persistence unit in a persistence-unit element in the persistence.xml file.

How to Specify the Persistence Unit Name

If you are developing your application in a Java EE environment, ensure that the persistence unit name is unique within each module. For example, you can define only one persistence unit with the name "EmployeeService" in an emp_ejb.jar file. The following example shows how to define the name of the persistence unit:

How to Specify the Transaction Type, Persistence Provider and Data Source

If you are developing your application in a Java EE environment, accept the default transaction type (see Section 6.2.1.2 "transaction-type" of the JPA Specification)–JTA (see JTA Transaction Management), and for the persistence provider setting, set the persistence provider in a provider element (see Section 6.2.1.2 "provider" of the JPA Specification). Specify the data source in a jta-data-source element, as the following example shows:

How to Specify Mapping Files

Apply the metadata to the persistence unit. This metadata is a union of all the mapping files and the annotations (if there is no xml-mapping-metadata-complete element). If you use one mapping orm.xml file) for your metadata, and place this file in a META-INF directory on the classpath, then you do not need to explicitly list it, because the EclipseLink persistence provider will automatically search for this file and use it. If you named your mapping files differently or placed them in a different location, then you must list them in the mapping-file elements in the persistence.xml file, as the following example shows:

How to Specify Managed Classes

Typically, you put all of the entities and other managed classes in a single JAR file, along with the persistence.xml file in the META-INF directory, and one or more mapping files (when you use XML mapping).

At the time EclipseLink persistence provider processes the persistence unit, it determines which set of entities, mapped superclasses, and embedded objects each particular persistence unit will manage.

At deployment time, EclipseLink persistence provider may obtain managed classes from any of the four sources. A managed class will be included if it is one of the following:

Note: If you are deploying your application in the Java EE environment, not EclipseLink persistence provider, but the application server itself will discover local classes. In the Java SE environment, you can use the exclude-unlisted-classes element (see Section 6.2.1.6 "mapping-file, jar-file, class, exclude-unlisted-classes" of the JPA Specification) to enable this functionality–EclipseLink persistence provider will attempt to find local classes if you set this element to false.

Classes in mapping files: the classes that have mapping entries, such as entity (see Section 10.1.2.10 "entity" of the JPA Specification), mapped-superclass (see Section 10.1.2.11 "mapped-superclass" of the JPA Specification) or embeddable (see Section 10.1.2.12 "embeddable" of the JPA Specification), in an XML mapping file.If these classes are in the deployed component archive, then they will already be on the classpath. If they are not, you must explicitly include them in the classpath.

Explicitly listed classes: the classes that are listed as class elements in the persistence.xml file.Consider listing classes explicitly if one of the following applies:

there are additional classes that are not local to the deployment unit JAR. For example, there is an embedded object class in a different JAR that you want to use in an entity in your persistence unit. You would list the fully qualified class in the class element in the persitence.xml file. You would also need to ensure that the JAR or directory that contains the class is on the classpath of the deployed component (by adding it to the manifest classpath of the deployment JAR, for example);

you want to exclude one or more classes that may be annotated as an entity. Even though the class may be annotated with the @Entity annotation, you do not want it treated as an entity in this particular deployed context. For example, you may want to use this entity as a transfer object and it needs to be part of the deployment unit. In this case, in the Java EE environment, you have to use the exclude-unlisted-classes element (see Section 6.2.1.6 "mapping-file, jar-file, class, exclude-unlisted-classes" of the JPA Specification) of the persistence.xml file–the use of the default setting of this element prevents local classes from being added to the persistence unit;

Additional JAR files of managed classes: the annotated classes in a named JAR file listed in a jar-file element (see Section 6.2.1.6 "mapping-file, jar-file, class, exclude-unlisted-classes" of the JPA Specification) in the persistence.xml file.You have to ensure that any JAR file listed in the jar-file element is on the classpath of the deployment unit. Do so by manually adding the JAR file to the manifest classpath of the deployment unit.Note that you must list the JAR file in the jar-file element relative to the parent of the JAR file in which the persistence.xml file is located. This matches what you would put in the classpath entry in the manifest file. The following example shows the structure of the emp.ear EAR file:

The following example shows the contents of the persistence.xml file, with the jar-file element containing "employee/emp-classes.jar" to reference the emp-classes.jar in the employee directory in the EAR file:

How to Add Vendor Properties

The last section in the persistence.xml file is the properties section. The properties element (see Section 6.2.1.7 "properties" of the JPA Specification) gives you the chance to supply EclipseLink persistence provider-specific settings for the persistence unit.

How to Set Up the Deployment Classpath

To be accessible to the EJB JAR, WAR, or EAR file, a class or a JAR file must be on the deployment classpath. You can achieve this in one of the following ways:

Put the JAR file in the manifest classpath of the EJB JAR or WAR file. Do this by adding a classpath entry to the META-INF/MANIFEST.MF file in the JAR or WAR file. You may specify one or more directories or JAR files, separating them by spaces. The following example shows how the manifest file classpath entry adds the employee/emp-classes.jar file and the employee/classes directory to the classpath of the JAR file that contains the manifest file:

Class-Path: employee/emp-classes.jar employee/classes

Place the JAR file in the library directory of the EAR file–this will make this JAR file available on the application classpath and accessible by all of the modules deployed within the EAR file. By default, this would be the lib directory of the EAR file, although you may configure it to be any directory in the EAR file using the library-directory element in the application.xml deployment descriptor. The following example shows the application.xml file:

What You May Need to Know About Persistence Unit Packaging Options

Java EE allows for persistence support in a variety of packaging configurations. You can deploy your application to the following module types:

EJB modules: you can package your entities in an EJB JAR. When defining a persistence unit in an EJB JAR, the persistence.xml file is not optional–you must create and place it in the META-INF directory of the JAR alongside the deployment descriptor, if it exists.

Web modules: you can use WAR file to package your entities. In this case, place the persistence.xml file in the WEB-INF/classes/META-INF directory. Since the WEB-INF/classes directory is automatically on the classpath of the WAR, specify the mapping file relative to that directory.

Persistence archives: a persistence archive is a JAR that contains a persistence.xml file in its META-INF directory and the managed classes for the persistence unit defined by the persistence.xml file. Use a persistence archive if you want to allow multiple components in different Java EE modules to share or access a persistence unit. The following example shows how to package entities in a persistence archive:

Once you created a persistence archive, you can place it in either the root or the application library directory of the EAR. Alternatively, you can place the persistence archive in the WEB-INF/lib directory of a WAR. This will make the persistence unit accessible only to the classes inside the WAR, but it enables the decoupling of the definition of the persistence unit from the web archive itself.

For more information, see Section 6.2 "Persistence Unit Packaging" of the JPA Specification.

What You May Need to Know About the Persistence Unit Scope

You can define any number of persistence units in single persistence.xml file. The following are the rules for using defined and packaged persistence units:

Persistence units are accessible only within the scope of their definition.

Persistence units names must be unique within their scope.

For more information, see Section 6.2.2 "Persistence Unit Scope" of the JPA Specification.

How to Perform an Application Bootstrapping

Outside of a container, use the createEntityManagerFactory method of the javax.persistence.Persistence class to create an entity manager factory. This method accepts a Map of properties and the name of the persistence unit. The properties that you pass to this method are combined with those that you already specified in the persistence.xml file. They may be additional properties or they may override the value of a property that you specified previously.

Note: This is a convenient way to set properties obtained from a program input, such as the command line.

This example shows how to take the user name and password properties from the command line and pass them to the EclipseLink persistence provider when creating the EntityManagerFactory.