Jump to: navigation, search

EclipseLink/UserGuide/JPA/Print Version

< EclipseLink‎ | UserGuide‎ | JPA
Revision as of 15:45, 25 November 2009 by James.sutherland.oracle.com (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Contents


Introduction to Java Persistence API

Elug draft icon.png For the latest EclipseLink documentation, please see http://www.eclipse.org/eclipselink/documentation/


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.

For more information, see the following:

What Do You Need to Develop with JPA

To start developing with JPA, you need the following:


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:

 @Entity
 public class Employee implements Serializable {
    private static final long serialVersionUID = -8865917134914502125L;
 ...
 }

For more information on entities, see the following:

persistence.xml File

Use the persistence.xml file to package your entities.

For more information and examples, see the following:

Object Relational Mapping Metadata

Object relational mapping metadata specifies the mapping of your domain model classes to the database.

You can express this metadata in the form of annotations and/or XML.


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:

Overriding Annotations with XML

XML mapping metadata may combine with and override annotation metadata. 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.


Container-Managed Entity Manager

In the Java EE environment, you acquire an entity manager by injecting it using the @PersistenceContext annotation (dependency injection), as the Obtaining an Entity Manager Through Dependency Injection example shows, or using a direct lookup of the entity manager in the JNDI namespace, as the Performing JNDI Lookup of an Entity Manager example shows.

Example 17-1

Obtaining an Entity Manager Through Dependency Injection

 @PersistenceContext 
 public EntityManager em;

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

Example 17-2

Performing JNDI Lookup of an Entity Manager

 @Stateless
 @PersistenceContext(name="ProjectEM", unitName="Project")
 public class ProjectSessionBean implements Project {
     @Resource 
     SessionContext ctx;
 
     public void makeCurrent() {
         try {
            EntityManager em = (EntityManager)ctx.lookup("ProjectEM");
            ...
     }
 }

See the following EclipseLink post for concurrency issues when using an EntityManager directly on a servlet outside of a function local variable instead of a Statelss session bean.

The container would manage the life cycle of this entity manager–your application does not have to create it or close it.

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

  • Section 3.1 "EntityManager"
  • Section 5.2.1 "Obtaining an Entity Manager in the Java EE Environment"
  • Section 5.3.1 "Obtaining an Entity Manager Factory in a Java EE Container"

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:


Application-Managed Entity Manager in the Java SE Environment

 public class Employee {
 
     public static void main(String[] args) {
         EntityManagerFactory emf =
             Persistence.createEntityManagerFactory("EmpService");
         EntityManager em = emf.createEntityManager();
     ...
         em.close();
         emf.close();
 }

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:

  • Section 5.2.2 "Obtaining an Application-managed Entity Manager"
  • Section 5.3.2 "Obtaining an Entity Manager Factory in a Java SE Environment"


Transaction Management

Transactions define when new, changed or removed entities are synchronized to the database.

JPA supports the following two types of transaction management:

Container-managed entity managers always use JTA transactions. Application-managed entity managers may use JTA or resource-local transactions. The default transaction type for Java EE application is JTA.

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.

  • Section 5.5.2 "Resource-local Entity Managers"
  • Section 5.5.2.1 "The EntityTransaction Interface"




Copyright Statement

Introduction to EclipseLink JPA

Elug draft icon.png For the latest EclipseLink documentation, please see http://www.eclipse.org/eclipselink/documentation/


This section introduces EclipseLink implementation of Java Persistence API.

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.

For more information, see Introduction to EclipseLink.

You can perform object-relational mapping with EclipseLink JPA by the means of doing the following:


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:

 @Entity
 public class Employee implements Serializable {
     ...
 }

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

For more information and examples, see the following:

EclipseLink defines a set of proprietary annotations. You can find them in the org.eclipselink.annotations package.

EclipseLink annotations expose some features of EclipseLink that are currently not available through the use of JPA metadata.


Using XML

You can use XML mapping metadata on its own, or in combination with annotation metadata, or you can use it to override the annotation metadata.

If you choose to include one or more mapping XML files in your persistence unit, each file must conform and be valid against the orm_1_0.xsd schema located at http://java.sun.com/xml/ns/persistence/orm_1_0.xsd. This schema defines a namespace called http://java.sun.com/xml/ns/persistence/orm that includes all of the ORM elements that you can use in your mapping file.

This example shows a typical XML header for a mapping file:

XML Header for Mapping File

 <?xml version="1.0" encoding="UTF-8"?>
 <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xdi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
                         http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
     version="1.0">

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.

EclipseLink provides a set of persistence unit properties that you can specify in your persistence.xml file, or in a property map file (eclipse.persistence.config.PersistenceUnitProperties). For more information, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.

Similar to EclipseLink annotation extensions, EclipseLink persistence unit properties expose some features of EclipseLink that are currently not available through the use of JPA metadata.

For more information, see Using EclipseLink JPA Extensions.

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.
  • Result - Entity A will contain the mapping b (from orm.xml), mapping c and d (from eclipselink-orm.xml)

Example 2

  • META-INF/orm.xml - defines Entity A with the mappings b and c
  • META-INF/some-other-mapping-file.xml - defines Entity B with mappings a and b
  • META-INF/eclipselink-orm.xml - defines Entity A with the mappings for c and d and Entity B with the mapping b and c
  • Result
    • Entity A will contain the mapping b (from orm.xml), mapping c and d (from eclipselink-orm.xml)
    • Entity B will contain the mapping a (from some-other-mapping-file), mappings b and c (from eclipselink-orm.xml)

Example 3

  • META-INF/orm.xml - defines Entity A with the mappings b and c.
  • META-INF/eclipse-orm.xml - defines Entity A with the mappings c and d.
  • META-INF/some-other-mapping-file.xml - defines Entity A with the mapping x.
  • Result - Entity A will contain the mapping b (from orm.xml), mapping c and d (from eclipselink-orm.xml) and mapping x (from some-other-mapping-file)

Example 4

  • META-INF/orm.xml - defines Entity A with the mappings b and c.
  • META-INF/extensions/eclipselink-orm.xml - defines defines Entity A with the mappings c and d.
    Note: This file is added through a <mapping-file> tag in the persistence.xml
  • Result - Exception generated for conficting specifications for mapping c.

Example 5

  • META-INF/orm.xml - defines Entity A with the mappings b and c.
  • META-INF/jpa-mapping-file.xml - defines Entity A with the mappings a and d.
  • META-INF/extensions/eclipse-mapping-file.xml - defines defines Entity A with the mappings c and d.
  • Result - Exception generated for conficting specifications for mapping c or d (which ever is processed first).

Overriding and Merging Rules

The following sections outlines elements defined in orm.xml and their specific overriding in greater detail.

Persistence Unit Metadata

In EclipseLink-ORM.XML, a persistence-unit-metadata specification merges or overrides the values of existing persistence-unit-metadata specification.

entity-mappings/persistence-unit-metadata Rule Description
xml-mapping-metadata-complete Full override If specified, the complete set of mapping metadata for the persistence unit is contained in the XML mapping files for the persistence unit.
persistence-unit-defaults/schema Full override If a schema setting exists, then the EclipseLink-ORM.XML's schema setting overrides the existing setting, or creates a new schema setting.
persistence-unit-defaults/catalog Full override If a catalog setting exists, then the EclipseLink-ORM.XML's catalog setting overrides the existing setting, or creates a new catalog setting
persistence-unit-defaults/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.
entity-mappings/persistence-unit-metadata/persistence-unit-defaults/cascade-persist Full override If a cascade-persist setting exists, then the EclipseLink-ORM.XML's cascade-persist setting overrides the existing setting, or creates a new cascade-persist setting.
entity-mappings/persistence-unit-metadata/persistence-unit-defaults/entity-listeners Merge 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.
attributes Merge and mapping level override 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, else 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 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.
attributes Merge and mapping level override 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, else creates new attributes.
association-override Merge and full override 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:

You can also use these annotations to fine-tune how your database maintains the identity of your entities.

For more information on the EclipseLink artifacts configured by these JPA metadata, refer to Configuring Primary Keys.


@Id

Use the @Id annotation to designate one or more persistent fields or properties as the entity's primary key.

For each entity, you must designate at least one of the following:


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.

Usage of @Id Annotation

 @Entity
 public class Employee implements Serializable {
     @Id
     private int empID;
     ...
 }

The @Id annotation supports the use of EclipseLink converters (see Using EclipseLink JPA Converters).

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).


Nonembedded Composite Primary Key Class

 public class EmployeePK implements Serializable {
 
     private String empName;
     private Date birthDay;
 
     public EmployeePK() {
     }
 
     public String getName() {
         return this.empName;
     }
 
     public void setName(String name) {
         this.empName = name;
     }
 
     public long getDateOfBirth() {
         return this.birthDay;
     }
 
     public void setDateOfBirth(Date date) {
         this.birthDay = date;
     }
 
     public int hashCode() {
         return (int)this.empName.hashCode();
     }
 
     public boolean equals(Object obj) {
         if (obj == this) return true;
         if (!(obj instanceof EmployeePK)) return false;
         if (obj == null) return false;
         EmployeePK pk = (EmployeePK) obj;
         return pk.birthDay = this.birthDay && pk.empName.equals(this.empName);
     }
 }

Usage of @IdClass Annotation

  @IdClass (EmployeePK.class)
 @Entity
 public class Employee implements Serializable{
 
     @Id String empName;
     @Id Date birthDay;
     ...
 }

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.


Embeddable Composite Primary Key Class

 @Embeddable
 public class EmployeePK implements Serializable {
 
     private String empName;
     private long empID;
 
     public EmployeePK() {
     }
 
     public String getName() {
         return this.empName;
     }
 
     public void setName(String name) {
         this.empName = name;
     }
 
     public long getId() {
         return this.empID;
     }
 
     public void setId(long id) {
         this.empID = id;
     }
 
     public int hashCode() {
         return (int)this.empName.hashCode()+ this.empID;
     }
 
     public boolean equals(Object obj) {
         if (obj == this) return true;
         if (!(obj instanceof EmployeePK)) return false;
         if (obj == null) return false;
         EmployeePK pk = (EmployeePK) obj;
         return pk.empID == this.empID && pk.empName.equals(this.empName);
     }
 }

Usage of @EmbeddedId Annotation

 @Entity
 public class Employee implements Serializable{
 
     @EmbeddedId
     EmployeePK primaryKey;
 
     public Employee {
     }
 
     public EmployeePK getPrimaryKey() {
         return primaryKey:
     }
 
     public void setPrimaryKey(EmployeePK pk) {
         primaryKey = pk;
     }
 
     ...
 }

For more information and examples, see Section 9.1.14 "EmbeddedId Annotation" of the JPA Specification.


@GeneratedValue

Use the @GeneratedValue annotation to enable EclipseLink persistence provider to generate unique identifiers for entity primary keys (see @Id).

This annotation lets you do the following:

  • 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.

    • TABLE – specify that EclipseLink persistence provider assign primary keys for the entity using an underlying database table to ensure uniqueness (see @TableGenerator).
    • SEQUENCE – specify that EclipseLink persistence provider use a database sequence (see @SequenceGenerator).
    • 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: IDENTITY strategy is supported on Sybase, DB2, SQL Server, MySQL, Derby, JavaDB, Informix, and Postgres databases.

      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.

      Using Automatic Id Generation

       @Entity
       public class Employee implements Serializable {
       
           @Id
           @GeneratedValue(strategy=GenerationType.AUTO)
           private int id;
           ...
       }


      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.

      For more information, see Table Sequencing.


      @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:

      • change the allocation size to match your application requirements or database performance parameters;
      • 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);
      • use a predefined sequence in an existing data model.

      The @SequenceGenerator annotation has the following attributes:

      • name – The name of the generator must match the name of a GeneratedValue with its strategy attribute set to SEQUENCE.

        You are required to specify the value of this attribute.
      • allocationSize – By default, EclipseLink persistence provider uses an allocation size of 50.

        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.

      Usage of @SequenceGenerator

       @Entity
       public class Employee implements Serializable {
           ...
           @Id
           @SequenceGenerator(name="Cust_Seq", allocationSize=25)
           @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="Cust_Seq")
           @Column(name="CUST_ID")
           public Long getId() {
               return id;
           }
           ...
       }

      For more information and examples, see Section 9.1.37 "SequenceGenerator Annotation" of the JPA Specification.

      For more information on the EclipseLink artifacts configured by these JPA metadata, refer to Descriptors and Sequencing.


      @TableGenerator

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

      • change the name of the primary key generator's table, because the name is awkward, a reserved word, incompatible with a preexisting data model, or invalid as a table name in your database;
      • change the allocation size to match your application requirements or database performance parameters;
      • 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.

      Usage of @TableGenerator

       @Entity
       public class Employee implements Serializable {
           ...
           @Id
           @TableGenerator(name="Emp_Gen", allocationSize=1)
           @GeneratedValue(strategy=GenerationType.TABLE, generator="Emp_Gen")
           @Column(name="CUST_ID")
           public Long getId() {
               return id;
           }
           ...
       }

      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.

      Usage of @Version Annotation

       @Entity
       public class Employee implements Serializable {
           ...
           @Version
           @Column(name="OPTLOCK")
           protected int getVersionNum() {
               return versionNum;
           }
           ...
       }

      The @Version annotation supports the use of EclipseLink converters (see Using EclipseLink JPA Converters).

      For more information, see the following:

      For more information on the EclipseLink artifacts configured by these JPA metadata, refer to Descriptors and Locking.

      Declaring Basic Property Mappings

      Simple Java types are mapped as part of the immediate state of an entity in its fields or properties. Mappings of simple Java types are called basic mappings.

      By default, EclipseLink persistence provider automatically configures a basic mapping for simple types.

      Use the following annotations to fine-tune how your database implements these mappings:

      For more information, see Using EclipseLink JPA Converters.


      @Basic

      By default, EclipseLink persistence provider automatically configures @Basic mapping for most Java primitive types, wrappers of the primitive types, and enumerated types.

      EclipseLink uses the default column name format of <field-name> or <property-name> in uppercase characters.

      You may explicitly place an optional @Basic annotation on a field or property to explicitly mark it as persistent.


      Note: The @Basic annotation is mostly for documentation purposes – it is not required for the field or property to be persistent.


      Use the @Basic annotation to do the following:

      • configure the fetch type to LAZY;
      • configure the mapping to forbid null values (for nonprimitive types) in case null values are inappropriate for your application.

      The @Basic annotation has the following attributes:

      • 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.


      Usage of the @Basic Annotation

       @Entity
       public class Employee implements Serializable {
           ...
           @Basic(fetch=LAZY)
           protected String getName() {
               return name;
           }
           ...
       }

      For more information and examples, see Section 9.1.18 "Basic Annotation" of the JPA Specification.

      For more information on EclipseLink direct mappings and relationship mappings, see Relational Mapping Types.


      @Enumerated

      By default, EclipseLink persistence provider persists the ordinal values of enumerated constants.

      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:

      You can use this annotation with the @Basic annotation.

      The @Enumerated annotation has the following attributes:

      • 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.


      Enumerated Constants

       public enum EmployeeStatus {FULL_TIME, PART_TIME, CONTRACT}
       public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}

      Usage of the @Enumerated Annotation

       @Entity
       public class Employee implements Serializable{
           ...
           public EmployeeStatus getStatus() {
               ...
           }
       
           @Enumerated(STRING)
           public SalaryRate getRate() {
               ...
           }
           ...
       }

      For more information and examples, see Section 9.1.21 "Enumerated Annotation" of the JPA Specification.


      @Temporal

      Use the @Temporal annotation to specify the database type that EclipseLink persistence provider should persist for persistent fields or properties of type java.util.Date and java.util.Calendar only.

      You can use this annotation with the @Basic annotation.

      The @Temporal annotation has the following attributes:

      • value – Set this attribute to the TemporalType that corresponds to database type you want EclipseLink persistence provider to use:
        • DATE – equivalent of java.sql.Date
        • TIME – equivalent of java.time.Date
        • TIMESTAMP – equivalent of java.sql.Timestamp

      You are required to specify the value of this attribute.

      This example shows how to use this annotation to specify that EclipseLink persistence provider should persist java.util.Date field startDate as a DATE (java.sql.Date) database type.


      Usage of the @Temporal Annotation

       @Entity
       public class Employee implements Serializable{
           ...
           @Temporal(DATE)
           protected java.util.Date startDate;
           ...
       }

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


      @Lob

      By default, EclipseLink persistence provider assumes that all persistent data can be represented as typical database data types.

      Use the @Lob annotation with the @Basic mapping to specify that a persistent property or field should be persisted as a large object to a database-supported large object type.

      A Lob may be either a binary or character type. The persistence provider infers the Lob type from the type of the persistent field or property.

      For String and character-based types, the default is Clob. In all other cases, the default is Blob.

      You can also use the @Column attribute columnDefinition (see Section 9.1.5 "Column Annotation" of the JPA Specification) to further refine the Lob type.

      The @Lob annotation does not have attributes.

      This example shows how to use this @Lob annotation to specify that persistent field pic should be persisted as a Blob.


      Usage of the @Lob Annotation

       @Entity
       public class Employee implements Serializable {
           ...
           @Lob
           @Basic(fetch=LAZY)
           @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
           protected byte[] pic;
           ...
       }

      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.

      This annotation can be used with @Entity (see Section 8.1 "Entity" of the JPA Specification), @MappedSuperclass), and @Embeddable.

      The @Transient annotation does not have attributes.

      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.


      Usage of the @Transient Annotation

       @Entity
       public class Employee implements Serializable {
           ...
           @Id
           int id;
       
           @Transient
           Session currentSession;
           ...
       }


      For more information and examples, see Section 9.1.16 "Transient Annotation" of the JPA Specification.


      Mapping Relationships

      EclipseLink persistence provider requires that you map relationships explicitly.

      Use the following annotations to specify the type and characteristics of entity relationships to fine-tune how your database implements these relationships:

      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.

      For more information, see Relational Mapping Types.

      You can access additional advanced mappings and mapping options through EclipseLink descriptor and mapping API using a DescriptorCustomizer Class.


      @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.

      Use the OneToOne annotation to do the following:

      • configure the fetch type to LAZY;
      • configure the mapping to forbid null values (for nonprimitive types) in case null values are inappropriate for your application;
      • 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.

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

      The Usage of @OneToOne Annotation - Customer Class and Usage of @OneToOne Annotation - CustomerRecord Class examples show how to use this annotation to configure a one-to-one mapping between Customer (the owning side) and CustomerRecord (the owned side).


      Usage of @OneToOne Annotation - Customer Class

       @Entity
       public class Customer implements Serializable {
           ...
           @OneToOne(optional=false)
           @JoinColumn(name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
           public CustomerRecord getCustomerRecord() { 
               return customerRecord;
           }
           ...
       }


      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.


      Usage of @OneToOne Annotation - CustomerRecord Class

       @Entity
       public class CustomerRecord implements Serializable {
           ...
           @OneToOne(optional=false, mappedBy="customerRecord")
           public Customer getCustomer() { 
               return customer;
           }
           ...
       }


      For more information and examples, see Section 9.1.23 "OneToOne Annotation" of the JPA Specification.

      For more information on EclipseLink direct mappings and relationship mappings, see Relational Mapping Types.

      For more information, see One-to-One Mapping and Configuring a Relational One-to-One Mapping.


      @ManyToOne

      By default, JPA automatically defines a ManyToOne mapping for a single-valued association to another entity class that has many-to-one multiplicity.

      Use the ManyToOne annotation to do the following:

      • configure the fetch type to LAZY;
      • configure the mapping to forbid null values (for nonprimitive types) in case null values are inappropriate for your application;
      • 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).

        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.
      • 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.


      Usage of @ManyToOne Annotation

       @Entity
       public class Order implements Serializable {
           ...
           @ManyToOne(optional=false)
           @JoinColumn(name="CUST_ID", nullable=false, updatable=false)
           public Customer getCustomer() { 
               return customer;
           }
           ...
       }


      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.

      For more information on EclipseLink direct mappings and relationship mappings, see Relational Mapping Types.


      @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.

        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, 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.

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

      The Usage of @OneToMany Annotation - Customer Class with Generics and Usage of @ManyToOne Annotation - Order Class with Generics examples show how to use this annotation to configure a one-to-many mapping between Customer (the owned side) and Order (the owning side) using generics.


      Usage of @OneToMany Annotation - Customer Class with Generics

       @Entity
       public class Customer implements Serializable {
           ...
           @OneToMany(cascade=ALL, mappedBy="customer")
           public Set<Order> getOrders() {  
               return orders;
           }
           ...
       }

      Usage of @ManyToOne Annotation - Order Class with Generics

       @Entity
       public class Order implements Serializable {
           ...
           @ManyToOne
           @JoinColumn(name="CUST_ID", nullable=false)
           public Customer getCustomer() { 
               return customer;
           }
           ...
       }

      For more information and examples, see Section 9.1.24 "OneToMany Annotation" of the JPA Specification.

      For more information on EclipseLink direct mappings and relationship mappings, see Relational Mapping Types.

      For more information on EclipseLink one-to-one mappings, see One-to-Many Mapping, and for information on how to configure these mappings, see Configuring a Relational One-to-Many Mapping.


      @ManyToMany

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

      Use the @ManyToMany annotation to do the following:

      • configure the fetch type to EAGER;
      • configure the mapping to forbid null values (for nonprimitive types) in case null values are inappropriate for your application;
      • 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.

        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, 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.

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

      The Usage of @ManyToMany Annotation - Employee Class with Generics and Usage of @ManyToMany Annotation - Project Class with Generics examples show how to use this annotation to configure a many-to-many mapping between Employee and Project using generics.


      Usage of @ManyToMany Annotation - Employee Class with Generics

       @Entity
       public class Employee implements Serializable {
           @Id
           private int id;
           private String name;
           @ManyToMany
           @JoinTable(name="EMP_PROJ",
                       joinColumns=
                            @JoinColumn(name="EMP_ID"),
                       inverseJoinColumns=
                            @JoinColumn(name="PROJ_ID)
           )
           private Collection<Project> projects;
           ...
       }


      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.


      Usage of @ManyToMany Annotation - Project Class with Generics

       @Entity
       public class Project implements Serializable {
           ...
           @ManyToMany(mappedBy="projects")
           public Set<Employee> getEmployees() { 
               return employees;
           }
           ...
       }

      For more information and examples, see Section 9.1.26 "ManyToMany Annotation" of the JPA Specification.

      For more information on EclipseLink direct mappings and relationship mappings, see Relational Mapping Types.

      For more information on EclipseLink one-to-one mappings, see Many-to-Many Mapping, and for information on how to configure these mappings, see Configuring a Relational Many-to-Many Mapping.


      @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;
      • an embedded composite primary key class (see @EmbeddedId).

      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.

        You are not required to provide value for this attribute.

      In the Project Entity Using @MapKey Annotation example, Project owns a one-to-many relationship to instances of Employee as a Map. The Project Entity Using @MapKey Annotation example shows how to use the @MapKey annotation to specify that the key for this Map is Employee field empPK, an embedded composite primary key (see the Employee Entity example) of type EmployeePK (see the Project Entity Using @MapKey Annotation example).


      Project Entity Using @MapKey Annotation

       @Entity
       public class Project implements Serializable {
           ...
           @OneToMany(mappedBy="project")
           @MapKey(name="empPK")
           public Map<EmployeePK, Employee> getEmployees() { 
               ...
           }
           ...
       }


      Employee Entity

       @Entity
       public class Employee implements Serializable {
           ...
           @EmbeddedId
           public EmployeePK getEmpPK() { 
               ...
           }
       
           @ManyToOne
           @JoinColumn(name="proj_id")
           public Project getProject() { 
               ...
           }
           ...
       }

      EmployeePK Composite Primary Key Class

       @Embeddable
       public class EmployeePk {
       
           String name;
           Date birthDate;
           ...
       }

      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.


      Project Entity Using @OrderBy Annotation

       @Entity
       public class Project implements Serializable {
           ...
           @ManyToMany(mappedBy="project")
           @OrderBy("lastname ASC, seniority DESC")
           public List<Employee> getEmployees() { 
               ...
           }
           ...
       }

      For more information and examples, see Section 9.1.28 "OrderBy Annotation" of the JPA Specification.


      Mapping Inheritance

      By default, EclipseLink persistence provider assumes that all persistent fields are defined by a single entity class.

      Use the following annotations if your entity class inherits some or all persistent fields from one or more superclasses:

      For more information, see Section 2.1.9 "Inheritance" of the JPA Specification.

      You can access advanced inheritance options through EclipseLink descriptor API using a DescriptorCustomizer class.


      @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.


      @Inheritance - Root Class Using JOINED

       import static javax.persistence.InheritanceType.JOINED;
       @Entity
       @Inheritance(strategy=JOINED)
       public class Customer implements Serializable {
       
           @Id
           private int customerId;
           ...
       }

      @Inheritance - Subclass Using JOINED

       @Entity
       public class ValuedCustomer extends Customer {
           ...
       }

      In the @Inheritance - Root Class Specifying its Discriminator Column example, by default, InheritanceType.SINGLE_TABLE applies to Customer and all its subclasses. In this example, the default discriminator table column DTYPE (@DiscriminatorColumn) is specified as having a discriminator type of INTEGER and the @DiscriminatorValue for Customer is specified as 1. The @Inheritance - Subclass Specifying its Discriminator Value example shows how to specify the discriminator value for subclass ValuedCustomer as 2. In this example, all the persistent properties of both Customer and ValuedCustomer will be mapped to a single table.

      @Inheritance - Root Class Specifying its Discriminator Column

       @Entity
       @DiscriminatorColumn(discriminatorType=DiscriminatorType.INTEGER)
       @DiscriminatorValue(value="1")
       public class Customer implements Serializable {
           ...
       }

      @Inheritance - Subclass Specifying its Discriminator Value

       @Entity
       @DiscriminatorValue(value="2")
       public class ValuedCustomer extends Customer {
           ...
       }

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

      • Section 2.1.9 "Inheritance"
      • Section 2.1.10 "Inheritance Mapping Strategies"
      • Section 9.1.29 "Inheritance Annotation"

      @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.

      Usage of the @MappedSuperclass Annotation

       @MappedSuperclass
       public class Employee implements Serializable {
       
           @Id
           protected Integer empId;
           @Version
           protected Integer version;
       
           @ManyToOne
           @JoinColumn(name="ADDR")
           protected Address address;
       
           ...
       }

      Extending a Mapped Superclass

       @Entity
       @AttributeOverride(name="address", column=@Column(name="ADDR_ID"))
       public class PartTimeEmployee extends Employee {
           @Column(name="WAGE")
           protected Float hourlyWage;
       
           ...
       }

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

      • Section 9.1.36 "MappedSuperclass Annotation"
      • Section 2.1.9.2 "Mapped Superclasses"
      • Section 2.1.10 "Inheritance Mapping Strategies"


      @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.

        Your @DiscriminatorValue must conform to this type.

        You are not required to specify the value of this attribute.
      • 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.

        Your @DiscriminatorValue must conform to this type.

        You are not required to specify the value of this attribute.
      • 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.


      @DiscriminatorColumn and @DiscriminatorValue - Root Class

       @Entity
       @Table(name="CUST")
       @Inheritance(strategy=SINGLE_TABLE)
       @DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
       @DiscriminatorValue(value="CUST")
       public class Customer implements Serializable {
           ...
       }

      @DiscriminatorValue - Subclass

       @Entity
       @DiscriminatorValue(value="VIP")
       public class ValuedCustomer extends Customer {
           ...
       }

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

      • Section 9.1.30 "DiscriminatorColumn Annotation"
      • Section 9.1.31 "DiscriminatorValue Annotation"
      • Section 2.1.10 "Inheritance Mapping Strategies"


      @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.


      @DiscriminatorColumn and @DiscriminatorValue - Root Class

       @Entity
       @Table(name="CUST")
       @Inheritance(strategy=SINGLE_TABLE)
       @DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
       @DiscriminatorValue(value="CUST")
       public class Customer implements Serializable {
           ...
       }

      @DiscriminatorValue - Subclass

       @Entity
       @DiscriminatorValue(value="VIP")
       public class ValuedCustomer extends Customer {
           ...
       }

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

      • Section 9.1.30 "DiscriminatorColumn Annotation"
      • Section 9.1.31 "DiscriminatorValue Annotation"
      • Section 2.1.10 "Inheritance Mapping Strategies"


      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:

      For information on EclipseLink aggregate descriptors, refer to Aggregate and Composite Descriptors in Relational Projects; for aggregates advanced configuration options, refer to EclipseLink API.


      @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.

      The @Embeddable annotation does not have attributes.

      The Usage of the @Embeddable Annotation example shows how to use this annotation to specify that class EmploymentPeriod may be embedded in an entity when used as the type for a persistent field annotated as @Embedded (see theUsage of the @Embedded Annotation and @Embedded examples).


      Usage of the @Embeddable Annotation

       @Embeddable
       public class EmploymentPeriod {
       
           java.util.Date startDate;
           java.util.Date endDate;
           ...
       }

      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.


      Usage of the @Embedded Annotation

       @Embeddable
       public class Employee implements Serializable {
           ...
           @Embedded
           @AttributeOverrides({
           @AttributeOverride(name="startDate", column=@Column(name="EMP_START")),
           @AttributeOverride(name="endDate", column=@Column(name="EMP_END"))})
           public EmploymentPeriod getEmploymentPeriod() {
           ...
           }
           ... 
       }

      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.

      To customize an association mapping to change its @JoinColumn (see Section 9.1.6 "JoinColumn Annotation" of the JPA Specification), use the @AssociationOverride annotation.

      The @AttributeOverride annotation has the following attributes:

      • column – The @Column that is being mapped to the persistent attribute. 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.

        You are required to specify the value of this attribute.

      The Usage of the @MappedSuperclass Annotation example shows a @MappedSuperclass that the entity in the Usage of the @AttributeOverride Annotation example extends. The Usage of the @AttributeOverride Annotation example shows how to use @AttributeOverride in the entity subclass to override the @Column defined (by default) in the @MappedSuperclass Employee for the basic mapping to Address.

      With the @AttributeOverride, the Employee table contains the following columns:

      • ID
      • VERSION
      • ADDR_STRING
      • WAGE

      Without the @AttributeOverride, the Employee table contains the following columns:

      • ID
      • VERSION
      • ADDRESS
      • WAGE


      Usage of the @MappedSuperclass Annotation

       @MappedSuperclass
       public class Employee {
       
           @Id
           protected Integer id;
           @Version
           protected Integer version;
           protected String address;
           ... 
       }

      Usage of the @AttributeOverride Annotation

       @Entity
       @AttributeOverride(name="address", column=@Column(name="ADDR_STRING"))
       public class PartTimeEmployee extends Employee {
       
           @Column(name="WAGE")
           protected Float hourlyWage;
           ...
       }

      For more information, see Section 9.1.10 "AttributeOverride Annotation" of the JPA Specification.


      @AttributeOverrides

      If you need to specify more than one @AttributeOverride, you must specify all your attribute overrides using a single @AttributeOverrides annotation.

      The @AttributeOverrides annotation has the following attributes:

      • value – To specify two or more attribute overrides, set value to an array of AttributeOverride instances.

        You are required to specify the value of this attribute.

      This example shows how to use this annotation to specify two attribute overrides.


      Usage of the @AttributeOverrides Annotation

       @Entity
       @AttributeOverrides({
           @AttributeOverride(name="address", column=@Column(name="ADDR_ID")),
           @AttributeOverride(name="id", column=@Column(name="PTID"))
       })
       public class PartTimeEmployee extends Employee {
       
           @Column(name="WAGE")
           protected Float hourlyWage;
       
           public PartTimeEmployee() {
           ...
           }
       
           public Float getHourlyWage() {
           ...
           }
       
           public void setHourlyWage(Float wage) {
           ...
           }
       }


      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).

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

      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.

        You are required to specify the value of this attribute.

      The Usage of the @MappedSuperclass Annotation example shows a @MappedSuperclass that the entity in the Usage of the @AssociationOverride Annotation example extends. The Usage of the @AssociationOverride Annotation example shows how to use @AssociationOverride in the entity subclass to override the @JoinColumn defined (by default) in the @MappedSuperclass Employee for the association to Address.

      With the @AssociationOverride, the Employee table contains the following columns:

      • ID
      • VERSION
      • ADDR_ID
      • WAGE

      Without the @AssociationOverride, the Employee table contains the following columns:

      • ID
      • VERSION
      • ADDRESS
      • WAGE


      Usage of the @MappedSuperclass Annotation

       @MappedSuperclass
       public class Employee {
       
           @Id
           protected Integer id;
           @Version
           protected Integer version;
           @ManyToOne
           protected Address address;
           ... 
       }

      Usage of the @AssociationOverride Annotation

       @Entity
       @AssociationOverride(name="address", joinColumns=@JoinColumn(name="ADDR_ID"))
       public class PartTimeEmployee extends Employee {
       
           @Column(name="WAGE")
           protected Float hourlyWage;
           ...
       }

      For more information, see Section 9.1.12 "AssociationOverride Annotation" of the JPA Specification.


      @AssociationOverrides

      If you need to specify more than one @AssociationOverride, you must specify all your association overrides using a single @AssociationOverrides annotation.

      The @AssociationOverrides annotation has the following attributes:

      • value – To specify two or more association overrides, set this attribute to an array of AssociationOverride instances.

        You are required to specify the value of this attribute.

      This example shows how to use this annotation to specify two association overrides.

      Usage of the @AssociationOverrides Annotation

       @Entity
       @AssociationOverrides({
           @AssociationOverride(name="address", joinColumn=@JoinColumn(name="ADDR_ID")),
           @AssociationOverride(name="phone", joinColumn=@JoinColumn(name="PHONE_NUM"))
       })
       public class PartTimeEmployee extends Employee {
       
           @Column(name="WAGE")
           protected Float hourlyWage;
           ...
       }

      For more information, see Section 9.1.13 "AssociationOverrides Annotation" of the JPA Specification.



      Copyright Statement

      Using EclipseLink JPA Extensions

      This page is now obsolete. Please see the EclipseLink JPA Extensions Guide for the current information.

      Configuring a EclipseLink JPA Application

      Elug draft icon.png For the latest EclipseLink documentation, please see http://www.eclipse.org/eclipselink/documentation/


      This section contains information on how you can configure your EclipseLink persistence project.

      When configuring an EclipseLink JPA application you cannot use the org.eclipselink.sessions.Project class, but you can still customize sessions and descriptors by using the customizer extensions (see Using EclipseLink JPA Extensions for Customization and Optimization).

      You can set up your EclipseLink JPA application using various IDEs.

      At run time, if the eclipselink.jar file is on the application classpath, you have the option to choose EclipseLink as a persistence provider for your application.


      Configuring Oracle Database Proxy Authentication for a JPA Application

      One of the features of the Oracle Database is proxy authentication. For more information, see Oracle Database Proxy Authentication.


      How to Provide Authenticated Reads and Writes of Secured Data Through the Use of an Exclusive Isolated Client Session

      If you use Oracle Virtual Private Database (VPD) (see Isolated Client Sessions and VPD), and you want to enable read and write access control for your EclipseLink JPA application, in the SessionCustomizer class set the connection policy to use exclusive connections, and define the descriptor for secured data as isolated (see Configuring Cache Isolation at the Descriptor Level). Consider the following example.

      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,

      Map properties = new HashMap();
      properties.put("eclipselink.jdbc.exclusive-connection.mode", "Isolated");
      properties.put("eclipselink.cache.shared.Employee", "false");
      ...
      EntityManagerFactory emf = Persistence.createEntityManagerFactory(properties);
      

      In the preceding example, an entity named Employee uses isolated cache and will be read and written through an exclusive connection.

      To specify that all entities are to use isolated cache, set the eclipselink.cache.shared.default property to false:

      properties.put("eclipselink.cache.shared.default", "false");
      

      For more information, see How to Use the Persistence Unit Properties for Caching.

      How to Provide Authenticated Writes for Database Auditing Purposes with a Client Session

      If you want to enable write access control for your EclipseLink JPA application, in your SessionCustomizer class provide the EntityManager with properties similar to the ones that the following example demonstrates.

      Map emProperties = new HashMap();
      emProperties.put("eclipselink.oracle.proxy-type", oracle.jdbc.OracleConnection.PROXYTYPE_USER_NAME);
      emProperties.put(oracle.jdbc.OracleConnection.PROXY_USER_NAME, "john");
      EntityManager em = emFactory.createEntityManager(emProperties);
      

      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:

      ((org.eclipse.persistence.internal.jpa.EntityManagerImpl)em.getDelegate()).setProperties(emProperties);
      

      JPA 2.0 defines a new setProperty method on EntityManager that could be used instead:

      em.setProperty("eclipselink.oracle.proxy-type", oracle.jdbc.OracleConnection.PROXYTYPE_USER_NAME);
      em.SetProperty(oracle.jdbc.OracleConnection.PROXY_USER_NAME, "john");
      

      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.

      For more information, see How to Use the Persistence Unit Properties for Caching.

      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:

      Map factoryProperties = new HashMap();
      factoryProperties.put("eclipselink.oracle.proxy-type", oracle.jdbc.OracleConnection.PROXYTYPE_USER_NAME);
      factoryProperties.put(oracle.jdbc.OracleConnection.PROXY_USER_NAME, "sarah");
      EntityManagerFactory emf = Persistence.createEntityManagerFactory(factoryProperties);
      
      // em1 does not specify its own proxy properties -
      // it uses proxy user "sarah" specified by the factory
      EntityManager em1 = emf.createEntityManager();
       
      Map emProperties = new HashMap();
      emProperties.put("eclipselink.oracle.proxy-type", oracle.jdbc.OracleConnection.PROXYTYPE_USER_NAME);
      emProperties.put(oracle.jdbc.OracleConnection.PROXY_USER_NAME, "john");
      
      // em2 uses its own proxy properties (proxy user "john"), 
      // regardless of whether or not factory has proxy properties
      EntityManager em2 = emf.createEntityManager(emProperties);
       
      // em3 does not use any proxy connection. 
      // It cancels proxy properties defined in the factory
      Map cancelProperties = new HashMap();
      cancelProperties.put("eclipselink.oracle.proxy-type", "");
      EntityManager em3 = emf.createEntityManager(cancelProperties);
      

      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.

      Setting Up Packaging

      You can package your application manually (see Packaging an EclipseLink JPA Application), or use an IDE.




      Copyright Statement

      Developing Applications Using EclipseLink JPA

      Elug draft icon.png For the latest EclipseLink documentation, please see http://www.eclipse.org/eclipselink/documentation/



      Using Application Components

      When developing an application with EclipseLink JPA, you need to know how to use the following application components:


      How to Obtain an Entity Manager Factory

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


      Obtaining an Entity Manager Factory in Java EE Application Server Environment

      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.

      @PersistenceUnit
      EntityManagerFactory emf;
      

      For more information, see the following:


      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:

       EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("Order");
       EntityManager em = emf.createEntityManager();

      For more information, see the following:


      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).

       @PersistenceContext
       EntityManager em;
       
       @PersistenceContext(type=PersistenceContextType.EXTENDED)
       EntityManager orderEM;

      The container manages the life cycle of the persistence context, as well as the creation and closing of the entity manager–your application does not have to be involved in this process.

      For more information, see the following:


      Obtaining an Entity Manager in Java SE Environment

      You obtain an application-managed entity manager from an entity manager factory.

      For more information and examples, see the following:


      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.

      Applications use the EntityManagerFactory interface for creating an application-managed entity manager (see Obtaining an Entity Manager in Java SE Environment).

      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

       SELECT ORDER
       FROM ORDER ORDER

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

      Simple Query to Find Some Objects

       SELECT ORDER
       FROM ORDER ORDER
       WHERE ORDER.shippingAddress.state = 'CA'

      For more information and examples, see the following:


      What You May Need to Know About Named and Dynamic Queries

      You can use the Query API to define both 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:


      Defining a Named Query

       @NamedQuery(name="findSalaryForNameAndDepartment",
                   query="SELECT e.salary " +
                         "FROM Employee.e " +
                         "WHERE e.department.name = :deptName AND " +
                         "      e.name = :empName")

      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:


      Defining Multiple Named Queries for an Entity

       @NamedQueries({
           @NamedQuery(name="Employee.findAll",
                       query="SELECT e FROM Employee.e"),
           @NamedQuery(name="Employee.findByPrimaryKey",
                       query="SELECT e FROM Employee.e WHERE e.id = :id"),
           @NamedQuery(name="Employee.findByName",
                       query="SELECT e FROM Employee.e WHERE e.name = :name"),
       })

      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.


      ''''' Creating a Named Query with Parameters'''''
       @PersistenceContext
       public EntityManager em;
       ...
       customers = em.createNamedQuery("findAllCustomersWithName")
                     .setParameter("custName", "Smith").getResultList();

      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.

      Defining a Named Query in an XML Mapping File

       <entity-mapping>
           ...
           <named-query name="findEmployeesWithName">
       
               <query>SELECT e FROM Employee e WHERE e.name LIKE :empName</query>
               <hint name="eclipselink.cache-usage" value="DoNotCheckCache"/>
           </named-query>
           ...
       <entity-mapping>

      Note: We recommend using named queries with query parameters.


      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.

      For more information and examples, see the following:

      Persisting Domain Model Changes

      How to Use JTA

      Information pending


      How to Use RESOURCE_LOCAL

      Information pending


      How to Configure Flushing and Set Flush Modes

      Information pending


      How to Manage a Life Cycle of an Entity

      Information pending


      Merging Detached Entity State

      Information pending


      Using Detached Entities and Lazy Loading

      Information pending

      For more information, see the following:


      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 = 60000
       WHERE 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

       DELETE FROM Employee e
       WHERE e.department IS NULL

      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.

      For more information and examples, see the following:


      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.

      Use the executeUpdate method of the Query interface to invoke bulk update and delete queries (see What You May Need to Know About Persisting with JP QL).

      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.

      For more information, see the following:


      Using EclipseLink JPA Extensions in Your Application Development

      This section describes the following:


      How to Use Extensions for Query

      Information pending


      Using Query Hints

      Information pending


      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 Query Hints

       public Employee findEmployeeNoCache(int empId) {
           Query q = em.createQuery("SELECT e FROM Employee e WHERE e.id = ?1");
           // force read from database
           q.setHint("eclipselink.cache-usage", "DoNotCheckCache");
           q.setParameter(1, empId);
           try {
               return (Employee)q.getSingleResult();
           }
           catch(NoResultException e) {
               return null;
           }
       }

      If you need execute this query frequently, you should use a named query. The following named query definition incorporates the cache hint from the Using Query Hints example.

      @NamedQuery(name="findEmployeeNoCache",
                  query="SELECT e FROM Employee e WHERE e.id = :empId",
                  hints={@QueryHint(name="eclipselink.cache-usage", 
                                    value="DoNotCheckCache")})
      

      The hints element accepts an array of @QueryHint annotations (see Section 8.3 "Annotations for Queries" of the JPA Specification), allowing you to set any number of hints for a query.

      For more information, see the following:

      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).

      For more information, see the following:


      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).

      For more information, see the following:


      How to Configure Fetch Groups

      By default, the EclipseLink persistence provider will use dynamic weaving to configure all applicable mappings to use fetch groups.

      For more information, see the following:


      How to Use Extensions for Caching

      Information pending


      What You May Need to Know About EclipseLink Caching

      The EclipseLink cache is an in-memory repository that stores recently read or written objects based on class and primary key values. EclipseLink uses the cache to do the following:

      • Improve performance by holding recently read or written objects and accessing them in-memory to minimize database access.
      • Manage locking and isolation level.
      • Manage object identity.

      EclipseLink uses the following two types of cache:

      • the session cache maintains objects retrieved from and written to the data source;
      • the unit of work cache holds objects while they participate in transactions.

      When a unit of work successfully commits to the data source, EclipseLink updates the session cache accordingly.

      For more information, see Cache.


      What You May Need to Know About Cache Coordination

      EclipseLink provides a distributed cache coordination feature that ensures data in distributed applications remains current.

      For more information, see the following:


      How to Configure Cascading

      Information pending

      For more information, see the following:


      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.


      For more information, see the following:


      How to Use EclipseLink Metadata

      Information pending


      Using EclipseLink Project

      Information pending


      Using sessions.xml File

      Information pending


      How to Use Events and Listeners

      Information pending

      <org.eclipse.persistence.sessions.SessionEventListener (eclipselink.session.event-listener)>

      <Configure a descriptor event listener to be added during bootstrap.>


      Using Session Events

      Information pending


      Using an Exception Handler

      Information pending


      What You May Need to Know About Database Platforms

      EclipseLink interacts with databases using SQL. The type of database platform you choose determines the specific means by which the EclipseLink runtime accesses the database.

      For more information, see Database Platforms.


      What You May Need to Know About Server Platforms

      You deploy your application to a specific Java EE application server.

      EclipseLink supports most versions of WebLogic, OC4J, SunAS, and WebSphere application servers.

      For more information, see the following:

      How to Optimize a JPA Application

      Information pending


      Using Statement Caching

      Information pending


      Using Batch Reading and Writing

      Information pending


      How to Perform Diagnostics

      Information pending


      Using Logging

      Information pending


      Using Profiling

      Information pending


      Using JMX

      Information pending




      Copyright Statement

      Packaging and Deploying EclipseLink JPA Applications

      Elug draft icon.png For the latest EclipseLink documentation, please see http://www.eclipse.org/eclipselink/documentation/



      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.

      For more information, see the following:


      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:

       <persistence-unit name="EmployeeService">

      For more information, see Section 6.2.1.1 "name" of the JPA Specification.


      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:

       <persistence-unit name="EmployeeService">
           <jta-data-source>jdbc/EmployeeServiceDS</jta-data-source>
       </persistence-unit>

      Typically, you would use the JNDI access to the data source. Make this data source available by configuring it in a server-specific configuration file or management console.

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

      • Section 6.2.1.2 "transaction-type"
      • Section 6.2.1.4 "provider"
      • Section 6.2.1.5 "jta-data-source, non-jta-data-source"

      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:

       <persistence-unit name="EmployeeService">
           <jta-data-source>jdbc/EmployeeServiceDS</jta-data-source>
           <mapping-file>META-INF/employee_service_queries.xml</mapping-file>
       </persistence-unit>

      Note that the orm.xml file is not listed in the previous example, because the persistence provider finds it by default.

      For more information, see the following:

      • Section 6.2.1.6 "mapping-file, jar-file, class, exclude-unlisted-classes" of the JPA Specification


      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;
        • you plan to run your application in the Java SE environment, and you list your classes explicitly because that is the only portable way to do so in Java SE (see How to Perform an Application Bootstrapping).
      • 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:
      emp.ear
          emp-ejb.jar
              META-INF/persistence.xml
          employee/emp-classes.jar
              examples/model/Empoyee.class
      

      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:

       <persitence-unit name="EmployeeService">
           <jta-data-source>jdbc/EmployeeServiceDS</jta-data-source>
           <jar-file>employee/emp-classes.jar</jar-file>
       </persitence-unit>

      You may choose to use any one or a combination of these mechanisms to include your managed classes in the persistence unit.

      For more information, see How to Deploy an Application to Generic Java EE 5 Application Servers.


      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.

      This example shows how to add EclipseLink-specific properties.

      Using EclipseLink Persistence Provider Properties

       <persitence-unit name="EmployeeService">
           ...
           <properties>
               <property name="eclipselink.logging.level" value="FINE"/>
       
               <property name="eclipselink.cache.size.default" value="500"/>
           </properties>
       </persitence-unit>

      For more information, see the following:

      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:
      <application ...>
          ...
          <library-directory>myDir/jars</library-directory>
      </application>
      

      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:
      emp.ear
          emp-persitence.jar
              META-INF/persistence.xml
              META-INF/orm.xml
              examples/model/Employee.class
              examples/model/Phone.class
              examples/model/Address.class
              examples/model/Department.class
              examples/model/Project.class
      

      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.

      Using Command-Line Persistence Properties

       public class EmployeeService {
       
           public static void main (String[] args) {
               Map props = new HashMap();
               props.put("eclipselink.jdbc.user", args[0]);
               props.put("eclipselink.jdbc.password", args[1]);
               EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService", props);
               ...
               emf.close();
           }
       }

      For more information, see the following:


      Deploying an EclipseLink JPA Application

      Deployment is the process of getting the application into an execution environment and running it.

      For more information, see the following:


      How to Deploy an Application to OC4J

      After packaging, you deploy your EclipseLink JPA application to OC4J to execute it and make it available to end users.

      You can deploy from a Java EE development tool such as JDeveloper or Eclipse.

      How to Deploy an Application to Generic Java EE 5 Application Servers

      Each persistence unit deployed into a Java EE container consists of a single persistence.xml file, any number of mapping files, and any number of class files.


      Note: If you are deploying to JBoss 4.2 server, refer to How to Configure JPA Application Deployment to JBoss 4.2 Application Server.




      Copyright Statement