Java Persistence API (JPA) Extensions Reference for EclipseLink, Release 2.7
  Go To Table Of Contents
 Search
 PDFComments
Comments

2 Annotation Extensions Reference

This chapter includes information on the EclipseLink extensions to the Java Persistence API (JPA) annotations. EclipseLink supports the Java Persistence API (JPA) 2.0 specification. It also includes many enhancements and extensions.

This chapter includes the following sections:

Functional Listing of Annotation Extensions

The following lists the EclipseLink annotation extensions, categorized by function:

Mapping Annotations

EclipseLink includes the following annotation extensions for mappings:

Converter Annotations

EclipseLink includes the following annotation extensions for converting data:

Caching Annotations

EclipseLink includes the following annotation extensions for caching:

Customization and Optimization Annotations

EclipseLink includes the following annotation extensions for customization and optimization.

Copy Policy Annotations

EclipseLink includes the following annotation extensions for copy policies:

Returning Policy Annotations

EclipseLink includes the following annotation extensions for returning policies:

Non-relational (NoSQL) Annotations

EclipseLink includes the following annotation extensions for non-relational datasources:

Alphabetical Listing of Annotation Extensions

The following lists the EclipseLink annotation extensions:


@AdditionalCriteria

Use @AdditionalCriteria to define parameterized views on data.

You can define additional criteria on entities or mapped superclass. When specified at the mapped superclass level, the additional criteria definition applies to all inheriting entities, unless those entities define their own additional criteria, in which case those defined for the mapped superclass are ignored.


Annotation Elements

Table 2-1 describes this annotation's elements.

Table 2-1 @AdditionalCriteria Annotation Elements

Attribute Description Default

value

(Required) The JPQL fragment to use as the additional criteria




Usage

Additional criteria can provide an additional filtering mechanism for queries. This filtering option, for example, allows you to use an existing additional JOIN expression defined for the entity or mapped superclass and allows you to pass parameters to it.

Set additional criteria parameters through properties on the entity manager factory or on the entity manager. Properties set on the entity manager override identically named properties set on the entity manager factory. Properties must be set on an entity manager before executing a query. Do not change the properties for the lifespan of the entity manager.


NoteNote:

Additional criteria are not supported with native SQL queries.



Examples

Specify additional criteria using the @AdditionalCriteria annotation or the <additional-criteria> element. The additional criteria definition supports any valid JPQL string and must use this as an alias to form the additional criteria. For example:

@AdditionalCriteria("this.address.city IS NOT NULL")

Example 2-1 shows additional criteria defined for the entity Employee and then shows the parameters for the additional criteria set on the entity manager.

Example 2-1 Using @AdditionalCriteria Annotation

Define additional criteria on Employee, as follows:

package model;
 
@AdditionalCriteria("this.company=:COMPANY")
public class Employee {

  ...
}

Set the property on the EntityManager. This example returns all employees of MyCompany.

entityManager.setProperty("COMPANY", "MyCompany");

Example 2-2 illustrates the same example as before, but uses the <additional-criteria> element in the eclipselink-orm.xml mapping file.

Example 2-2 Using <additional-criteria> XML

<additional-criteria>
  <criteria>this.address.city IS NOT NULL</criteria>
</additional-criteria>

Uses for Additional Criteria

Uses for additional criteria include:

Multitenancy

In a multitenancy environment, tenants (users, clients, organizations, applications) can share database tables, but the views on the data are restricted so that tenants have access only to their own data. You can use additional criteria to configure such restrictions.


NoteNote:

In most cases, you use the @Multitenant annotation in multitenancy environments instead, as shown.


Example 2-3 Multitenancy Example 1

The following example restricts the data for a Billing client, such as a billing application or billing organization:

@AdditionalCriteria("this.tenant = 'Billing'")

Example 2-4 Multitenancy Example 2

The following example could be used in an application used by multiple tenants at the same time. The additional criteria is defined as:

@AdditionalCriteria("this.tenant = :tenant")

When the tenant acquires its EntityManagerFactory or EntityManager, the persistence/entity manager property tenant is set to the name of the tenant acquiring it. For example,

Map properties = new HashMap();
properties.put("tenant", "ACME");
EntityManagerFactory emf = Persistence.createEntityManagerFactory(properties);

Or

Map properties = new HashMap();
properties.put("tenant", "ACME");
EntityManager em = factory.createEntityManager(properties);

Soft Delete

The following example filters data that is marked as deleted (but which still exists in the table) from a query:

@AdditionalCriteria("this.isDeleted = false")

Data History

The following example returns the current data from a query, thus filtering out any out-of-date data, for example data stored in a history table.

@AdditionalCriteria("this.endDate is null")

NoteNote:

EclipseLink also provides specific history support, via HistoryPolicy . See Tracking Changes Using History Policy at http://wiki.eclipse.org/EclipseLink/Examples/JPA/History.


Temporal Filtering

The following example filters on a specific date:

@AdditionalCriteria("this.startDate <= :viewDate and this.endDate >= :viewDate")

Shared Table

For a shared table, there may be inheritance in the table but not in the object model. For example, a SavingsAccount class may be mapped to an ACCOUNT table, but the ACCOUNT table contains both savings account data (SAVINGS) and checking account (CHECKING) data. You can use additional criteria to filter out the checking account data.


See Also

For more information, see:


@Array

Use @Array to define object-relational data types supported by specific databases, such as Oracle VARRAY types or PostgreSQL JDBC Array types.


Annotation Elements

Table 2-2 describes this annotation's elements.

Table 2-2 @Array Annotation Elements

Annotation Element Description Default

databaseType

(Required) The name of the database array structure type


targetClass

(Optional only if the collection field or property is defined using Java generics; otherwise Required) The class (basic or embeddable) that is the element type of the collection

Parameterized type of the collection.



Usage

Use @Array on a collection attribute that is persisted to an Array type. The collection can be of basic types or embeddable class mapped using a Struct.


Examples

Example 2-5 shows how to use this annotation with an Oracle VARRAY type.

Example 2-5 Using @Array with Oracle VARRAY

VARRAY DDL:
CREATE TYPE TASKS_TYPE AS VARRAY(10) OF VARCHAR(100)
@Struct
@Entity
public class Employee {
    @Id
    private long id;
    @Array(databaseType="TASKS_TYPE")
    private List<String> tasks;
}

Example 2-6 shows how to use this annotation with an PostgreSQL Struct type.

Example 2-6 Using @Array with PostgreSQL Struct

DDL:
CREATE TABLE EMPLOYEE (ID BIGINT, TASKS TEXT[])
@Struct
@Entity
public class Employee {
    @Id
    private long id;
    @Array(databaseType="TEXT")
    private List<String> tasks;
}


See Also

For more information, see the following:


@BatchFetch

Use @BatchFetch to read objects related to a relationship mapping (such as @OneToOne, @OneToMany, @ManyToMany, and @ElementCollection) to be read in a single query.


Annotation Elements

Table 2-3 describes this annotation's elements.

Table 2-3 @BatchFetch Annotation Elements

Annotation Element Description Default

size

Default size of the batch fetch, used only when BatchFetchType=IN to define the number of keys in each IN clause

256 or the query's pageSize (for cursor queries)

BatchFetchType

(Optional) The type of batch fetch to use:

  • JOIN – The original query's selection criteria is joined with the batch query

  • EXISTS – Uses an SQL EXISTS clause and a sub-select in the batch query instead of a JOIN

  • IN – Uses an SQL IN clause in the batch query, passing in the source object IDs.

JOIN



Usage

Batch fetching allows for the optimal loading of a tree. Setting the @BatchFetch annotation on a child relationship of a tree structure causes EclipseLink to use a single SQL statement for each level. For example, consider an object with an EMPLOYEE and PHONE table in which PHONE has a foreign key to EMPLOYEE. By default, reading a list of employees' addresses by default requires n queries, for each employee's address. With batch fetching, you use one query for all the addresses.

Using BatchFetchType=EXISTS does not require an SQL DISTINCT statement (which may cause issues with LOBs) and may be more efficient for some types of queries or on specific databases.

When using BatchFetchType=IN, EclipseLink selects only objects not already in the cache. This method may work better with cursors or pagination, or in situations in which you cannot use a JOIN. On some databases, this may only work for singleton IDs.


Examples

The following examples show how to use this annotation (and XML) with different batch fetch types.

Example 2-7 Using JOIN BatchFetch Type

@OneToOne
@BatchFetch(BatchFetchType.JOIN)
private Address address;
<one-to-one name="address">
    <batch-fetch type="JOIN" />
</one-to-one>

 

Example 2-8 Using EXISTS BatchFetch Type

@BatchFetch(BatchFetchType.EXISTS)
@OneToOne
public Map<String, String> getStringMap() {
return stringMap;
}
<one-to-one name="StringMap">
    <batch-fetch type="EXISTS"/>
</one-to-one>

Example 2-9 Using IN BatchFetch Type

@BatchFetch(BatchFetchType.IN, size=50)
@OneToOne
public Map<String, String> getStringMap() {
return stringMap;
}
 
<one-to-one name="StringMap">
    <batch-fetch type="IN" size="50" />
</one-to-one>


See Also

For more information, see:


@Cache

Use @Cache (in place of the JPA @Cachable annotation) to configure the EclipseLink object cache. By default, EclipseLink uses a shared object cache to cache all objects. You can configure the caching type and options on a per class basis to allow optimal caching.


Annotation Elements

Table 2-4 describes this annotation's elements.

Table 2-4 @Cache Annotation Elements

Annotation Element Description Default

type

(Optional) Set this attribute to the type (org.eclipse.persistence.annotations.CacheType enumerated type) of the cache that you will be using:

  • FULL

  • WEAK

  • SOFT

  • SOFT_WEAK

  • HARD_WEAK

  • CACHE (not recommended)

  • NONE (not recommended, use isolation=ISOLATED instead)

You can override this attribute with these persistence unit properties:

  • eclipselink.cache.type.<ENTITY>

  • eclipselink.cache.type.default

CacheType.SOFT_WEAK

size

(Optional) Set this attribute to an int value to define the size of cache to use (number of objects).

100

isolation

(Optional) The caching level of the Entity:

  • shared – Entity instances will be cached within the EntityManagerFactory/ServerSession level

  • isolated – The Entity and its data is not stored in the shared cache, but is isolated to the Persistence Context/UnitOfWork or IsolatedClientSession

  • protected – Entity state information will be cached in the shared cache, but Entity instances will not be shared

shared

expiry

(Optional) The int value to enable the expiration of the cached instance after a fixed period of time (milliseconds). Queries executed against the cache after this will be forced back to the database for a refreshed copy.

no expiry

expiryTimeOfDay

(Optional) Specific time of day (org.eclipse.persistence.annotations.TimeOfDay) when the cached instance will expire. Queries executed against the cache after this will be forced back to the database for a refreshed copy.

no expiry

alwaysRefresh

(Optional) Set to a boolean value of true to force all queries that go to the database to always refresh the cache

false

refreshOnlyIfNewer

(Optional) Set to a boolean value of true to force all queries that go to the database to refresh the cache only if the data received from the database by a query is newer than the data in the cache (as determined by the optimistic locking field)

Note:

  • This option only applies if one of the other refreshing options, such as alwaysRefresh, is already enabled.

  • A version field is necessary to apply this feature.

false

disableHits

(Optional) Set to a boolean value of true to force all queries to bypass the cache for hits, but still resolve against the cache for identity. This forces all queries to hit the database.

false

coordinationType

(Optional) Set this attribute to the cache coordination mode (org.eclipse.persistence.annotations.CacheCoordinationType enumerated type).

  • SEND_OBJECT_CHANGES – Sends a list of changed objects, including data about the changes. This data is merged into the receiving cache.

  • INVALIDATE_CHANGED_OBJECTS – Sends a list of the identities of the objects that have changed. The receiving cache invalidates the objects (rather than changing any of the data).

  • SEND_NEW_OBJECTS_WITH_CHANGES – Same as SEND_OBJECT_CHANGES excepts it also includes any newly-created objects from the transaction

  • NONE – Does not cache coordination

You must also configure cache coordination in your persistence unit properties. See "Caching".

SEND_OBJECT_CHANGES

databaseChangeNotificationType

(Optional) The database change notification mode:

  • Invalidate – Invalidates the EclipseLink cache when a database change event is received for an object.

  • None – No database change events will be processed. The database event listener must also be configured for the persistence unit/session.

INVALIDATE



Usage

Use the @Cache annotation instead of the JPA @Cachable annotation to provide additional caching configuration.

You can define the @Cache annotation on the following:

If you define the @Cache annotation on an inheritance subclass, the annotation will be ignored. If you define the @Cache annotation on @Embeddable EclipseLink will throw an exception.

Caching in EclipseLink

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:

For more information about the EclipseLink cache and its default behavior, see:

EclipseLink defines the following entity caching annotations:

EclipseLink also provides a number of persistence unit properties that you can specify to configure the cache. These properties may compliment or provide an alternative to the usage of annotations.

For more information, see "Caching".


Examples

Example 2-10 illustrates an @Cache annotation.

Example 2-10 Using @Cache Annotation

...
@Entity
@Cache(
  type=CacheType.SOFT, // Cache everything until the JVM decides memory is low.
  size=64000  // Use 64,000 as the initial cache size.
  expiry=36000000,  // 10 minutes
  coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS  // if cache coordination is used, only send invalidation messages.
)
public class Employee {
  ...
} 

Example 2-11 shows how to use this annotation in the eclipselink-orm.xml file.

Example 2-11 Using <cache> XML

<entity-mappings
  xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm 
  http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd"
  version="2.4">
    <entity name="Employee" class="org.acme.Employee" access="FIELD">
      <cache type="SOFT" size="64000" expiry="36000000" coordination-type="INVALIDATE_CHANGED_OBJECTS"/>
    </entity>
</entity-mappings>

You can also specify caching properties at the persistence unit level (in the persistence.xml file) as shown here:

Example 2-12 Specifying Caching in persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_2_0.xsd"
  version="2.0">
    <persistence-unit name="acme" transaction-type="RESOURCE_LOCAL">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
          <property name="eclipselink.cache.shared.default" value="false"/>
          <property name="eclipselink.cache.shared.Employee" value="true"/>
          <property name="eclipselink.cache.type.Employee" value="SOFT"/>
          <property name="eclipselink.cache.size.Employee" value="64000"/>
        </properties>
    </persistence-unit>
</persistence>


See Also

For more information, see:


@CacheIndex

Use @CacheIndex to define a cached index. Cache indexes are used only when caching is enabled.


Annotation Elements

Table 2-5 describes this annotation's elements.

Table 2-5 @CacheIndex Annotation Elements

Annotation Element Description Default

columnNames

(Optional) The set of columns on which to define the index. Not required when annotated on a field/method.


updateable

(Optional) Specify if the indexed field is updateable.

If true, the object will be re-indexed on each update or refresh.

true



Usage

A cache index allows singleResult queries to obtain a cache hit when querying on the indexed fields. A resultList query cannot obtain cache hits, as it is unknown if all of the objects are in memory, (unless the cache usage query hint is used).

The index should be unique. If it is not, the first indexed object will be returned.

You can use @CacheIndex on an Entity class or on an attribute. The column is defaulted when defined on a attribute.


Examples

Example 2-13 shows an example of using the @CacheIndex annotation.

Example 2-13 Using @CacheIndex Annotation

@Entity
@CacheIndex(columnNames={"F_NAME", "L_NAME"}, updateable=true)
public class Employee {
  @Id
  private long id;
  @CacheIndex
  private String ssn;
  @Column(name="F_NAME")
  private String firstName;
  @Column(name="L_NAME")
  private String lastName;
}

Example 2-14 shows an example of using the <cache-index> XML element in the eclipselink-orm.xml file.

Example 2-14 Using <cache-index> XML

<?xml version="1.0"?>
<entity-mappings
  xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd"
  version="2.4">
    <entity name="Employee" class="org.acme.Employee" access="FIELD">
        <cache-index updateable="true">
            <column-name>F_NAME</column-name>
            <column-name>L_NAME</column-name>
        </cache-index>
        <attributes>
            <id name="id"/>
            <basic name="ssn">
                <cache-index/>
            </basic>
            <basic name="firstName">
                <column name="F_NAME"/>
            </basic>
            <basic name="lastName">
                <column name="L_NAME"/>
            </basic>
        </attributes>
    </entity>
</entity-mappings>

Example 2-15 shows an example query using a cache index.

Example 2-15 Caching an Index Query

Query query = em.createQuery("Select e from Employee e where e.firstName = :firstName and e.lastName = :lastName");
query.setParameter("firstName", "Bob");
query.setParameter("lastName", "Smith");
Employee employee = (Employee)query.getSingleResult();


See Also

For more information, see:


@CacheIndexes

Use @CacheIndexes to define a set of @CacheIndex on an entity.


Annotation Elements

Table 2-6 describes this annotation's elements.

Table 2-6 @CacheIndexes Annotation Elements

Annotation Element Description Default

CacheIndex[]

An array of cache indexes




Examples

See "@CacheIndex" for examples of using the @CacheIndexes annotation.


See Also

For more information, see:


@CacheInterceptor

Use @CacheInterceptor on an entity to intercept all EclipseLink cache access to the entity instead of responding to cache operations through an event.


Annotation Elements

Table 2-7 describes this annotation's elements.

Table 2-7 @CacheInterceptor Annotation Elements

Annotation Element Description Default

value

The class to be used to intercept EclipseLink's cache access




Usage

Once set, the specified class will receive all caching calls. Existing EclipseLink cache settings will continue to be used, any calls allowed to continue to the EclipseLink cache will execute against the configured cache.

When using with an entity in inheritance, you should define the @CacheInterceptor on the root of the inheritance hierarchy.


Examples

Example 2-16 shows how to integrate an external cache with EclipseLink.

Example 2-16 Using @CacheInterceptor Annotation

In this example, the Employee class intercepts all EclipseLink calls to the internal EclipseLink cache and redirects them to the Oracle Coherence Grid cache (CoherenceInterceptor).

import oracle.eclipselink.coherence.integrated.cache.CoherenceInterceptor;
import org.eclipse.persistence.annotations.Customizer;
 
@Entity
@CacheInterceptor(value = CoherenceInterceptor.class)
public class Employee {
...
}

Example 2-17 shows an example of using the <cache-interceptor> XML element in the eclipselink-orm.xml file.

Example 2-17 Using <cache-interceptor> XML

<entity class="Employee">
    <cache-interceptor class="CoherenceInterceptor"/>
...
</entity>


See Also

For more information, see:


@CascadeOnDelete

Use the @CascadeOnDelete annotation to specify that a delete operation performed on a database object is cascaded on secondary or related tables.

ON DELETE CASCADE is a database foreign key constraint option that automatically removes the dependent rows.


Annotation Elements

There are no elements for this annotation.


Usage

You can place @CascadeOnDelete on any relationship in which the target is defined as foreign key to the source Entity.

Add the annotation on the source relationship: @OneToOne, @OneToMany, @ManyToMany, and @ElementCollection You can also add @CascadeOnDelete to an Entity with a @SecondaryTable or JOINED inheritance. Table 2-8 describes the affect of placing @CascadeOnDelete on these different elements

Table 2-8 Using @Cascade on Different Elements

Element Effect of @CascadeOnDelete

Entity

Defines that secondary or joined inheritance tables should cascade the delete on the database

OneToOne mapping

The deletion of the related object is cascaded on the database.

This is only allowed for mappedBy/target-foreign key OneToOne mappings (because of constraint direction).

OneToMany mapping

For a OneToMany using a mappedBy or JoinColumn, the deletion of the related objects is cascaded on the database.

For a OneToMany using a JoinTable, the deletion of the join table is cascaded on the database (target objects cannot be cascaded even if private because of constraint direction).

ManyToMany mapping

The deletion of the join table is cascaded on the database (target objects cannot be cascaded even if private because of constraint direction).

ElementCollection mapping

The deletion of the collection table is cascaded on the database.


@CascadeOnDelete has the following behavior:


Examples

Example 2-18 shows the cascading deletion of the Employee secondary table and all of its owned relationships.

Example 2-18 Using @CascadeOnDelete Annotation

@Entity
@SecondaryTable(name="EMP_SALARY")
@CascadeOnDelete
public class Employee{
    @Id
    private long id;
    private String firstName;
    private String lastName;
    @Column(table="EMP_SALARY")
    private String salary;
    @OneToOne(mappedBy="owner", orphanRemoval=true, cascade={CascadeType.ALL})
    @CascadeOnDelete
    private Address address;
    @OneToMany(mappedBy="owner", orphanRemoval=true, cascade={CascadeType.ALL})
    @CascadeOnDelete
    private List<Phone> phones;
    @ManyToMany
    @JoinTable(name="EMP_PROJ")
    @CascadeOnDelete
    private List<Project> projects;
    ...
}

In the eclipselink-orm.xml descriptor file, specify cascade on delete as shown in Example 2-19

Example 2-19 Using <cascade-on-delete> XML

...
<cascade-on-delete>true</cascade-on-delete>
...


See Also

For more information, see:


@ChangeTracking

Use @ChangeTracking to specify the org.eclipse.persistence.descriptors.changetracking.ObjectChangePolicy. This policy computes change sets for the EclipseLink commit process and optimizes the transaction by including objects in the change set calculation that have at least one changed attribute.


Annotation Elements

Table 2-9 describes this annotation's elements.

Table 2-9 @ChangeTracking Annotation Elements

Annotation Element Description Default

ChangeTrackingType

(Optional) The change tracking policy to use:

  • ATTRIBUTE – The object's set method is weaved to raise change events to collect changes as they are made.

    Requires usage of weaving, and LAZY collection relationships, or eager weaving.

  • OBJECT – The object's set method is weaved to mark the object as dirty. Any dirty objects are compared against a copy of their original state for changes on commit or flush operations.

    Requires usage of weaving, and LAZY collection relationships, or eager weaving.

  • DEFERRED – All managed objects are compared against a copy of their original state for changes on commit or flush.

    Does not require weaving.

  • AUTO – Does not set any change tracking policy; change tracking will be determined at runtime.

AUTO



Usage

Use this annotation to configure an alternative change policy, if the automatic policy is having issues with your application. Using @ChangeTracking may improve commit performance for objects with few attributes or objects with many changed attributes.


NoteNote:

When using change tracking with ATTRIBUTE or OBJECT, if you modify an object's field through reflection, EclipseLink will not detect the change. However, if you use DEFERRED, EclipseLink will detect the change.



Examples

Example 2-20 shows how to use @ChangeTracking to set the unit of work's change policy.

Example 2-20 Using @ChangeTracking Annotation

@ChangeTracking(DEFERRED)
@Entity
public class Employee {
    ...
}

Example 2-21 shows how to use the <change-tracking> element in the eclipselink-orm.xml file.

Example 2-21 Using <change-tracking> XML

<entity class="Employee"
    <change-tracking type="DEFERRED"/>
...
</entity>

Example 2-22 shows how to configure change tracking in the persistence unit persistence.xml file or by importing a property map.

Example 2-22 Specifying Change Tracking in persistence.xml

Using persistence.xml file:

<property name="eclipselink.weaving.changetracking" value="false"/>

Using property map:

import org.eclipse.persistence.config.PersistenceUnitProperties;
propertiesMap.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "false");


See Also

For more information, see:


@ClassExtractor

Use @ClassExtractor to define a custom class indicator in place of providing a discriminator column.


Annotation Elements

Table 2-10 describes this annotation's elements.

Table 2-10 @ClassExtractor Annotation Elements

Annotation Element Description Default

java.lang.Class

(Required) The name of the class extractor to apply to the entity's descriptor




Usage

If you are mapping to an existing database, and the tables do not have a discriminator column you can still define inheritance using the @ClassExtractor annotation or <class-extractor> element. The class extractor takes a class that implements the ClassExtractor interface. An instance of this class is used to determine the class type to use for a database row. The class extractor must define a extractClassFromRow method that takes the database Record and Session.

If a class extractor is used with SINGLE_TABLE inheritance, the rows of the class type must be able to be filtered in queries. This can be accomplished by setting an onlyInstancesExpression or withAllSubclassesExpression for branch classes. These can be set to Expression objects using a DescriptorCustomizer.


Examples

Example 2-23 shows an example of using ClassExtractor to define inheritance.

Example 2-23 Using @ClassExtractor Annotation

@Entity
@Table(name="MILES_ACCOUNT")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@ClassExtractor(AirMilesClassExtractor.class)
@Customizer(AirMilesCustomizer.class)
public class AirMilesAccount implements Serializable {
    @Id
    private Long id;
    @Basic
    private String totalMiles;
    @Basic
    private String milesBalance;
    ...
}
 
@Entity
@Customizer(PreferredCustomizer.class)
public class PreferredAccount extends AirMilesAccount {
    ...
}
 
public class AirMilesClassExtractor implements ClassExtractor {
    public void extractClassFromRow(Record row, Session session) {
        if (row.get("TOTALMILES").lessThan(100000)) {
            return AirMilesAccount.class;
        } else {
            return PreferredAccount.class;
        }
    }
}
 
public class AirMilesCustomizer implements DescriptorCustomizer {
    public void customize(ClassDescriptor descriptor) {
        ExpressionBuilder account = new ExpressionBuilder();
        Expression expression = account.getField("TOTALMILES").lessThan(100000);
        descriptor.getInheritancePolicy().setOnlyInstancesExpression(expression);
    }
}
 
public class PreferredCustomizer implements DescriptorCustomizer {
    public void customize(ClassDescriptor descriptor) {
        ExpressionBuilder account = new ExpressionBuilder();
        Expression expression = account.getField("TOTALMILES").greaterThanEqual(100000);
        descriptor.getInheritancePolicy().setOnlyInstancesExpression(expression);
    }
}

Example 2-24 shows how to use the <class-extractor> element in the eclipselink-orm.xml file.

Example 2-24 Using <class-extractor> XML

<entity class="AirMilesAccount">
    <table name="MILES_ACCOUNT"/>
    <inheritance strategy="SINGLE_TABLE"/>
    <class-extractor class="AirMilesClassExtractor"/>
...
</entity>
 
<entity class="PreferredAccount">
    <customizer class="PreferredCustomizer"/>
...
</entity>


See Also

For more information, see:


@CloneCopyPolicy

Use @CloneCopyPolicy to specify an org.eclipse.persistence.descriptors.copying.CloneCopyPolicy on an Entity.


Annotation Elements

Table 2-11 describes this annotation's elements.

Table 2-11 @CloneCopyPolicy Annotation Elements

Annotation Element Description Default

method

(Optional) The method that will be used to create a clone for comparison with EclispeLink's DeferredChangeDetectionPolicy


workingCopyMethod

(Optional) The workingCopyoMethod that will be used to create a clone that will be used when registering an object in an EclipseLink UnitOfWork




NoteNote:

You must specify either a method or workingCopyMenthod.



Usage

The clone method should perform a shallow clone of the object. This can be used to clone non-persistent fields from a instance in the shared cache.

You can specify @CloneCopyPolicy on an Entity, MappedSuperclass, or Embeddable class.


Examples

Example 2-25 and Example 2-26 show several examples of the @CloneCopyPolicy annotation and <clone-copy-policy> XML element, respectively.

Example 2-25 Using @CloneCopyPolicy Annotation

@CloneCopyPolicy(method="myClone")
@CloneCopyPolicy(method="myClone", workingCopyMethod="myWorkingCopyClone")
@CloneCopyPolicy(workingCopyMethod="myWorkingCopyClone")

Example 2-26 Using <clone-copy-policy> XML

<clone-copy-policy type="copy" method="myClone" workingCopyMethod="myWorkingCopyClone"/>
<clone-copy-policy type="copy" workingCopyMethod="myWorkingCopyClone"/>
<clone-copy-policy type="copy" method="myClone"/>
 


See Also

For more information, see:


@CompositeMember

Use @CompositeMember to indicate that a class belongs to a composite persistence unit.

It should be used if target type is a primitive type and @CollectionTable designates the table that belongs to composite member persistence unit other than the source composite member persistence unit. This allows the source and target to be mapped to different databases.


Annotation Elements

Table 2-12 describes this annotation's elements.

Table 2-12 @CompositeMember Annotation Elements

Annotation Element Description Default

value

The name of a target composite member persistence unit to which element table belongs (if differs from source composite member persistence unit




Usage

The @CompositeMember annotation is ignored unless it is in a composite member persistence unit. It may be used in conjunction with @ElementCollection and @CollectionTable annotations.


Examples

You can configure the CompositeMember using annotations or the eclipselink-orm.xml file, as shown in these examples.

Example 2-27 Using @CompositeMember Annotation

@ElementCollection()
@CollectionTable(name = "MBR1_RESPONS", joinColumns=@JoinColumn(name="EMP_ID"))
@CompositeMember("branch-database")
@Column(name = "DESCRIPTION")
public Collection<String> getResponsibilities() {
    return responsibilities;
}

Example 2-28 Using <composite-member> XML

<element-collection name="responsibilities" composite-member="branch-database">
  <column name="DESCRIPTION"/>
  <collection-table name="XML_MBR3_RESPONS">
    <join-column name="EMP_ID"/>
  </collection-table>
</element-collection>


See Also

For more information, see:


@ConversionValue

Use @ConversionValue to specify the database and object values for an ObjectTypeConverter.


Annotation Elements

Table 2-13 describes this annotation's elements.

Table 2-13 @ConversionValue Annotation Elements

Annotation Element Description Default

dataValue

(Required) The database value


objectValue

(Required) The object value




Usage

The JPA specification allows you to map an Enum to database columns using the @Enumerated annotation, when the database value is either the name of the Enum or its ordinal value. With EclipseLink, you can also map an Enum to a coded value, using a converter.


Examples

In Example 2-29, the enum Gender(MALE, FEMALE) is mapped to a single character in the database where M=MALE and F=FEMALE.

Example 2-29 Using @ConversionValue Annotation

@ObjectTypeConverter(name = "gender", objectType = Gender.class, dataType = String.class, conversionValues = {
  @ConversionValue(objectValue = "Male", dataValue = "M"),
  @ConversionValue(objectValue = "Female", dataValue = "F") })

...

@Basic
@Convert("gender")
private Gender gender = Gender.Male;

Example 2-30 illustrates the same function using XML.

Example 2-30 Using <conversion-value> XML

<object-type-converter name="gender" object-type="model.Gender   "data-type="java.lang.String">
  <conversion-value object-value="Male" data-value="M" />
  <conversion-value object-value="Female" data-value="F" />
</object-type-converter>

...

<basic name="gender">
  <column name="GENDER" />
  <convert>gender</convert>
</basic>


See Also

For more information, see:


@Convert

Use @Convert to specify that a named converter should be used with the corresponding mapped attribute.


Annotation Elements

Table 2-14 describes this annotation's elements.

Table 2-14 @Convert Annotation Elements

Annotation Element Description Default

value

(Optional) The String name for your converter

none



Usage

The @Convert has the following reserved names:


Examples

Example 2-31 shows how to use the @Convert annotation to define the gender field.

Example 2-31 Using the @Convert Annotation

@Entity
 @Table(name="EMPLOYEE")
 @Converter(
     name="genderConverter",
         converterClass=org.myorg.converters.GenderConverter.class
 )
 public class Employee implements Serializable{
     ...
     @Basic
     @Convert("genderConverter")
     public String getGender() {
         return gender;
     }
     ...
 }


See Also

For more information, see:


@Converter

Use the @Converter annotation to specify a custom converter for modification of the data value(s) during the reading and writing of a mapped attribute.


Annotation Elements

Table 2-15 describes this annotation's elements.

Table 2-15 @Converter Annotation Elements

Annotation Element Description Default

name

The String name for your converter, must be unique across the persistence unit

none

converterClass

The class of your converter. This class must implement the org.eclipse.persistence.mappings.converters.Converter interface.

none



Usage

Use @Converter to define a named converter that can be used with mappings. A converter can be defined on an entity class, method, or field. Specify a converter with the @Convert annotation on a Basic or ElementCollection mapping.

Using non-JPA Converter Annotations

EclipseLink provides a set of non-JPA converter annotations (in addition to the JPA default type mappings):

The persistence provider searches the converter annotations in the following order:

  1. @Convert

  2. @Enumerated

  3. @Lob

  4. @Temporal

  5. Serialized (automatic)

Specify the converters on the following classes:

Use the converters with the following mappings:

An exception is thrown if a converter is specified with any other type of mapping annotation.


Examples

Example 2-32 shows how to use the @Converter annotation to specify a converter class for the gender field.

Example 2-32 Using the @Converter Annotation

@Entity
 public class Employee implements Serializable{
    ...
     @Basic
     @Converter (
         name="genderConverter",
         converterClass=org.myorg.converters.GenderConverter.class
     )
     @Convert("genderConverter")
     public String getGender() {
         return gender;
     }
     ...
 }

Example 2-33 shows how to use the <converter> element in the eclipselink-orm.xml file.

Example 2-33 Using <converter> XML

<entity class="Employee">
...
    <attributes>
    ...
      <basic name="gender">
        <convert>genderConverter</convert>
        <converter name="genderConverter" class="org.myorg.converters.GenderConverter"/>
      </basic>
    ...
    </attributes>
</entity>


See Also

For more information, see:


@Converters

Use @Converters annotation to define multiple @Converter elements.


Annotation Elements

Table 2-16 describes this annotation's elements.

Table 2-16 @Converters Annotation Elements

Annotation Element Description Default

Converter[]

(Required) An array of converters




Examples

See "@Converter" for an example of this annotation.


See Also

For more information, see:


@CopyPolicy

Use @CopyPolicy to set an org.eclipse.persistence.descriptors.copying.CopyPolicy on an entity to produce a copy of the persistent element.


Annotation Elements

Table 2-17 describes this annotation's elements.

Table 2-17 @CopyPolicy Annotation Elements

Annotation Element Description Default

java.lang.Class

(Required) The class of the copy policy. The class must implement org.eclipse.persistence.descriptors.copying.CopyPolicy.




Usage

You can specify @CopyPolicy on an Entity, MappedSuperclass, or Embeddable class.


Examples

Example 2-34 shows how to use this annotation.

Example 2-34 Using @CopyPolicy Annotation

@Entity
  @Table(name="EMPLOYEE")
  @CopyPolicy(mypackage.MyCopyPolicy.class)
  public class Employee implements Serializable {
    ...
  }

Example 2-35 shows how to use the <copy-policy> element in the eclipselink-orm.xml file.

Example 2-35 Using <copy-policy> XML

<entity class="Employee">
  <table name="EMPLOYEE"/>
  <copy-policy class="mypackage.MyCopyPolicy"/>
...
</entity>


See Also

For more information, see:


@Customizer

Use @Customizer to specify a class that implements org.eclipse.persistence.config.DescriptorCustomizer and is to run against an entity's class descriptor after all metadata processing has been completed.


Annotation Elements

Table 2-18 describes this annotation's elements.

Table 2-18 @Customizer Annotation Elements

Annotation Element Description Default

java.lang.Class

(Required) The name of the descriptor customizer to apply to the entity's descriptor




Usage

Use this annotation to customize or extend the mapping metadata through the EclipseLink native API. With @Customizer, you can access additional EclipseLink functionality and configurations.

You can specify @Customizer on an Entity, MappedSuperclass, or Embeddable class.


NoteNote:

A @Customizer is not inherited from its parent classes.



Examples

Example 2-36 show how to use the @Customizer annotation with the following DescriptorCustomer:

public class MyCustomizer implements DescriptorCustomizer {
  public void customize(ClassDescriptor descriptor) {
    DirectToFieldMapping genderMapping = (DirectToFieldMapping)descriptor.getMappingForAttributeName("gender");
    ObjectTypeConverter converter = new ObjectTypeConverter();
    convert.addConversionValue("M", Gender.MALE);
    convert.addConversionValue("F", Gender.FEMALE);
    genderMapping.setConverter(converter);
  }
}

Example 2-36 Using @Customizer Annotation

@Entity
 @Table(name="EMPLOYEE")
 @Customizer(mypackage.MyCustomizer.class)
 public class Employee implements Serializable {
     ...
 }

Example 2-37 show how to use the <customizer> element in the eclipselink-orm.xml file.

Example 2-37 Using <customizer> XML

<entity class="Employee">
  <table name="EMPLOYEE"/>
  <customizer class="mypackage.MyCustomizer"/>
...
</entity>


See Also

For more information, see:


@DeleteAll

Use @DeleteAll to indicate that when an relationship is deleted, EclipseLink should use a delete all query. This typically happens if the relationship is PrivateOwned and its owner is deleted. In that case, the members of the relationship will be deleted without reading them in.


Annotation Elements

There are no elements for this annotation.


Usage


WARNING:

Use this annotation with caution. EclipseLink will not validate whether the target entity is mapped in such a way as to allow the delete all to work.



Examples

Example 2-38 shows how to use @DeleteAll on a relationship mapping.

Example 2-38 Using @DeleteAll Annotation

@Entity
public class Department {
  ...
  @OneToMany(mappedBy = "department")
  @PrivateOwned
  @DeleteAll
  public List<Equipment> getEquipment() {
    return equipment;
    }
  ...
  }
 

Example 2-38 shows how to use the <delete-all> element in the eclipselink-orm.xml file.

Example 2-39 Using <delete-all> XML

<entity class="Department">
  ...
  <attributes>
    <one-to-many name="equipment" target-entity="Equipment" mapped-by="department">
      <private-owned/>
      <delete-all/>
    </one-to-many>
...
</attributes>
</entity>


See Also

For more information, see:


@DiscriminatorClass

Use @DiscriminatorClass with a @VariableOneToOne annotation to determine which entities will be added to the list of types for the mapping.


Annotation Elements

Table 2-19 describes this annotation's elements.

Table 2-19 @DiscriminatorClass Annotation Elements

Annotation Element Description Default

discriminator

(Required) The discriminator to be stored in the database


value

(Required) The class to be instantiated with the discriminator




Usage

The @DiscriminatorClass annotation can be specified only within a @VariableOneToOne mapping.


Examples

See "@VariableOneToOne" for an example of a variable one-to-one mapping with @DiscriminatorClass.


See Also

For more information, see:


@ExcludeDefaultMappings

Use @ExcludeDefaultMappings to specify that no default mapping should be added to a specific class. Instead, EclipseLink will use only mappings that are explicitly defined by annotations or the XML mapping file.


Annotation Elements

There are no elements for this annotation.


Usage

You can specify @ExcludeDefaultMappings on an Entity, MappedSuperclass, or Embeddable class.


Examples

Example 2-40 shows how to use the @ExcludeDefaultMapping annotation.

Example 2-40 Using the @ExcludeDefaultMappings Annotation

@ExcludeDefaultMappings
@Entity
public class Dealer {
    @Id
    private long id;
    @Basic
    private String name;
    // These would be ignored
    private List<Card> deck;
    private List<Card> hand;
    ...
}


See Also

For more information, see:


@ExistenceChecking

Use @ExistenceChecking to specify how EclipseLink should check to determine if an entity is new or exists.

On merge() operations, use @ExistenceChecking to specify if EclipseLink uses only the cache to determine if an object exists, or if the object should be read (from the database or cache). By default the object will be read from the database.


Annotation Elements

Table 2-20 describes this annotation's elements.

Table 2-20 @ExistenceChecking Annotation Elements

Annotation Element Description Default

ExistenceType

(Optional) Set the existence checking type:

  • ASSUME_EXISTENCE

  • ASSUME_NON_EXISTENCE

  • CHECK_CHACHE

  • CHECK_DATABASE

CHECK_CACHE



Usage

You can specify @ExistenceChecking on an Entity or MappedSuperclass.

EclipseLink supports the following existence checking types:


Examples

Example 2-41 shows how to use this annotation.

Example 2-41 Using @ExistenceChecking Annotation

@Entity
@Cache(type=CacheType.HARD_WEAK,  expiryTimeOfDay=@TimeOfDay(hour=1))
@ExistenceChecking(ExistenceType.CHECK_DATABASE)
public  class  Employee  implements  Serializable  { 
...
}


See Also

For more information, see:


@FetchAttribute

Use @FetchAttribute to improve performance within a fetch group; it allows on-demand loading of a group of an object's attributes. As a result, the data for an attribute might not be loaded from the datasource until an explicit access call occurs.

This avoids loading all the data of an object's attributes if the user requires only some of the attributes.


Annotation Elements

Table 2-21 describes this annotation's elements.

Table 2-21 @FetchAttribute Annotation Elements

Annotation Element Description Default

name

(Required) Name of the fetch attribute




Usage

EclipseLink provides two types of fetch groups:

You should extensively review your use cases when using fetch groups. In many cases, additional round-trips will offset any gains from deferred loading.


Examples

Example 2-42 shows how to use @FetchAttribute within a @FetchGroup annotation.

Example 2-42 Using @FetchAttribute Annotation

@Entity
@FetchGroup(name="basic-fetch-group", attributes={
        @FetchAttribute(name="id"), 
        @FetchAttribute(name="name"),
        @FetchAttribute(name="address")}) 
public class Person {
 
   @Id
   private int id;
 
   private String name;
 
   @OneToOne(fetch=LAZY)
   private Address address;
 
   @ManyToOne(fetch=EAGER)
   private ContactInfo contactInfo;

Example 2-43 Using <fetch-group> XML

<fetch-group name="basic-fetch-group">
    <attribute name="id"/>
    <attribute name="name"/>
    <attribute name="address"/>
</fetch-group>


See Also

For more information, see:


@FetchGroup

Use @FetchGroup to load a group of attributes on demand, as needed.

This avoids wasteful practice of loading all data of the object's attributes, if the user is interested in only partial of them. However, it also means that the data for an attribute might not be loaded from the underlying data source until an explicit access call for the attribute first occurs.


Annotation Elements

Table 2-22 describes this annotation's elements.

Table 2-22 @FetchGroup Annotation Elements

Annotation Element Description Default

FetchAttribute[] attributes

(Required) The list of attributes to fetch

none

java.lang.String name

(Required) The fetch group name

none

boolean load

(Optional) Indicates whether all relationship attributes specified in the fetch group should be loaded.

false



Usage

You should perform a careful use case analysis when using @FetchGroup; any gains realized from the deferred loading could be offset by the extra round-trip.

EclipseLink supports fetch groups at two levels:

You can use fetch groups only when using weaving or when individual classes that define them explicitly implement the org.eclipse.persistence.queries.FetchGroupTracker interface.

When using a fetch group, you can define a subset of an object's attributes and associate the fetch group with a query. When you execute the query, EclipseLink retrieves only the attributes in the fetch group. EclipseLink automatically executes a query to fetch all the attributes excluded from this subset when and if you call a get method on any one of the excluded attributes.

You can define more than one fetch group for a class. You can optionally designate at most one such fetch group as the default fetch group. If you execute a query without specifying a fetch group, EclipseLink will use the default fetch group, unless you configure the query otherwise.

Before using fetch groups, it is recommended that you perform a careful analysis of system use. In many cases, the extra queries required to load attributes not in the fetch group could well offset the gain from the partial attribute loading.


Examples

Example 2-44 shows how to use this annotation.

Example 2-44 Using @FetchGroup Annotation

@FetchGroup(name="names", attributes={
    @FetchAttribute(name="firstName"), 
    @FetchAttribute(name="lastName")})

Example 2-45 shows how to use this feature in the eclipselink-orm.xml file.

Example 2-45 Using <fetch-group> XML

<entity class="model.Employee">
    <secondary-table name="SALARY" />
    <fetch-group name="names">
        <attribute name="firstName" />
        <attribute name="lastName" />
    </fetch-group>
...

You can also use a named fetch group with a query, as shown in Example 2-46.

Example 2-46 Using a Named Fetch Group on a Query

TypedQuery query = em.createQuery("SELECT e FROM Employee e", Employee.class);
 
query.setHint(QueryHints.FETCH_GROUP_NAME, "names");


See Also

For more information, see:


@FetchGroups

Use @FetchGroups to define a group of @FetchGroup.


Annotation Elements

Table 2-23 describes this annotation's elements.

Table 2-23 @FetchGroups Annotation Elements

Annotation Element Description Default

FetchGroup

(Required) An array of fetch groups (@FetchGroup)




Usage

You can specify @FetchGroups on an Entity or MappedSuperclass.

You can also enable or disable fetch groups through weaving for the persistence unit.


Examples

See "@FetchGroup" for an example of using fetch groups.

Example 2-47 shows how to configure fetch groups in the persistence unit persistence.xml file or by importing a property map.

Example 2-47 Specifying Fetch Groups in persistence.xml

Using persistence.xml file:

<property name="eclipselink.weaving.fetchgroups" value="false"/>

Using property map:

import org.eclipse.persistence.config.PersistenceUnitProperties;
propertiesMap.put(PersistenceUnitProperties.WEAVING_FETCHGROUPS, "false");


See Also

For more information, see:


@Field

Use @Field to define a structured data type's field name for an object mapped to NoSql data.


Annotation Elements

Table 2-24 describes this annotation's elements.

Table 2-24 @Field Annotation Elements

Annotation Element Description Default

name

(Optional) The data type's name of the field




Usage

The @Field annotation is a generic form of the @Column annotation, which is not specific to relational databases. You can use @Field to map EIS and NoSQL data.


Examples

See "@NoSql" for an example of the @Field annotation.


See Also

For more information, see:


@HashPartitioning

Use @HashPartitioning to partition access to a database cluster by the hash of a field value from the object (such as the object's location or tenant). The hash indexes into the list of connection pools.


Annotation Elements

Table 2-25 describes this annotation's elements.

Table 2-25 @HashPartitioning Annotation Elements

Annotation Element Description Default

name

(Required) The name of the partition policy. The name must be unique within the persistence unit.


partitionColumn

(Required) The database column or query parameter by which to partition queries


connectionPools

(Optional) List of connection pool names across which to partition

All defined pools in the ServerSession

unionUnpartitionableQueries

(Optional) Specify if queries that do not contain the partition hash should be sent to every database and union the result.

False



Usage

All write or read requests for objects with the hash value are sent to the server. Queries that do not include the field as a parameter will be:

You can enable partitioning on an Entity, relationship, query, or session/persistence unit. Partition policies are globally named (to allow reuse) and must set using the @Partitioned annotation.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA to ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "@Partitioned" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@Index

An index is a database structure defined for a table, to improve query and look-up performance for a set of columns. Use the @Index annotation in code or the <index> element in the eclipselink-orm.xml descriptor to create an index on a table.

An index can be defined on an entity or on an attribute. For the entity it must define a set of columns to index.

Index creation is database specific. Some databases may not support indexes. Most databases auto-index primary key and foreign key columns. Some databases support advanced index DDL options. To create more advanced index DDL, a DDL script or native query can be used.


Annotation Elements

Table 2-26 describes this annotation's elements.

Table 2-26 @Index Annotation Elements

Annotation Element Description Default

java.lang.String catalog

(Optional) The catalog of the INDEX

Default catalog

java.lang.String[] columnNames

(Not required when annotated on a field or method) Specify the set of columns to define the index on.

For an Entity, none.

For an attribute, the attribute's column.

java.lang.String name

(Optional) The name of the INDEX

<table>_<column>_INDEX (but a name should be provided)

java.lang.String schema

(Optional) The schema of the INDEX

Default schema

java.lang.String table

(Optional) The table to define the index on; defaults to entities primary table.

The entity's primary table.

boolean unique

(Optional) Specify whether the index is unique or non-unique.

false



Usage

Use @Index annotation to index any attributes or columns that will commonly be used in queries.


Examples

This example defines three indexes, one on first name, one on last name, and a multiple column index on first name and last name.

Example 2-48 Using @Index Annotation

@Entity
@Index(name="EMP_NAME_INDEX", columns={"F_NAME","L_NAME"})
public class Employee{
    @Id
    private long id;
    @Index
    @Column(name="F_NAME")
    private String firstName;
    @Index
    @Column(name="L_NAME")
    private String lastName;
    ...
}

You can also create an index in the eclipselink-orm.xml descriptor using <index>, as shown in the following example. Define columns using the <column> subelement. All the attributes supported in the @Index annotation are also supported in the <index> element.

Example 2-49 Using <index> XML

<index name="EMP_NAME_INDEX" table="EMPLOYEE" unique="true">
    <column>F_NAME</column>
    <column>L_NAME</column>
</index>


See Also

For more information see:


@Indexes

Use @Indexes to define a set of database indexes for an Entity.


Annotation Elements

Table 2-27 describes this annotation's elements.

Table 2-27 @Indexes Annotation Elements

Annotation Element Description Default

Index[]

An array of database indexes




Examples

See "@Index" for an example of using the @Index annotation.


See Also

For more information see:


@InstantiationCopyPolicy

Use @InstantiationCopyPolicy to set an org.eclipse.persistence.descriptors.copying.InstantiationCopyPolicy on an Entity.


Annotation Elements

There are no elements for this annotation.


Usage

The copy policy specifies how EclipseLink clones objects to and from the shared cache. With @InstantiationCopyPolicy, in order to clone an object EclipseLink will create a new instance of the object and copy each persistent attribute. Alternative methods include @CloneCopyPolicy, which clones the object.

Cloning is more efficient than creating a new instance and maintains transient or non-persistent attribute values. If you do not need transient or non-persistent attribute values in the shared cache, then use @InstantiationCopyPolicy.

The default EclipseLink copy policy depends on your configuration:

You can specify @InstantiationCopyPolicy on an Entity, MappedSuperclass, or Embeddable entity.


Examples

Example 2-50 shows how to use this annotation.

Example 2-50 Using @InstantiationCopyPolicy Annotation

@Entity
@InstantiationCopyPolicy
public class Employee {
    ...
    transient List events = new ArrayList();
}

Example 2-51 shows how to use this extension in the eclipselink-orm.xml file.

Example 2-51 Using <instantiation-copy-policy> XML

<entity name="Employee" class="org.acme.Employee" access="FIELD">
    <instantiation-copy-policy/>
    ...
</entity>


See Also

For more information, see:


@JoinFetch

Use the @JoinFetch annotation to enable the joining and reading of the related objects in the same query as the source object.


NoteNote:

You should set join fetching at the query level, as not all queries require joining.



Annotation Elements

Table 2-28 describes this annotation's elements.

Table 2-28 @JoinFetch Annotation Elements

Annotation Element Description Default

value

(Optional) Set this attribute to the org.eclipse.persistence.annotations.JoinFetchType enumerated type of the fetch that you will be using.

The following are the valid values for the JoinFetchType:

  • INNER—This option provides the inner join fetching of the related object.

    Note: Inner joining does not allow for null or empty values.

  • OUTER—This option provides the outer join fetching of the related object.

    Note: Outer joining allows for null or empty values.

JoinFetchType.INNER



Usage

You can specify the @JoinFetch annotation for the following mappings:

Alternatively, you can use batch fetching which is more efficient, especially for collection relationships.


Examples

The following example shows how to use the @JoinFetch annotation to specify Employee field managedEmployees.

Example 2-52 Using @JoinFetch Annotation

@Entity
 public class Employee implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="owner")
    @JoinFetch(value=OUTER)
    public Collection<Employee> getManagedEmployees() {
        return managedEmployees;
    }
    ...
 }

Example 2-53 shows how to use this extension in the eclipselink-orm.xml file.

Example 2-53 Using <join-fetch> in XML

<one-to-many name="managedEmployees">
    <join-fetch>OUTER</join-fetch>
</one-to-many>


See Also

For more information, see:


@JoinField

Use @JoinField to define a structured data type's foreign key field for an object mapped to NoSql data.


Annotation Elements

Table 2-29 describes this annotation's elements.

Table 2-29 @JoinField Annotation Elements

Annotation Element Description Default

name

(Optional) The name of the foreign key/ID reference field in the source record


referencedFieldName

(Optional) The name of the ID field in the target record




Usage

The @JoinField annotation is a generic form of the @JoinColumn annotation, which is not specific to relational databases. You can use @JoinField to map EIS and NoSQL data.


Examples

These examples show how to use this extension as an annotation and in XML.

Example 2-54 Using @JoinField Annotation

@Entity
@NoSql
public class Order {
    ...
    @ManyToOne
    @JoinField(name="customerId")
    private Customer customer;
}

Example 2-55 Using <join-field> in XML

<entity name="Order" class="org.acme.Order">
    <no-sql/>
    ...
    <many-to-one name="customer">
        <join-field name="customerId"/>
    </many-to-one>
</entity>


See Also

For more information, see:


@JoinFields

Use @JoinFields to define a set of @JoinField annotations on a relationship.


Annotation Elements

Table 2-30 describes this annotation's elements.

Table 2-30 @JoinFields Annotation Elements

Annotation Element Description Default

JoinField[]J

An array of join fields




Examples

See "@JoinField" for an example of using the @Index annotation.


See Also

For more information, see:


@MapKeyConvert

Use @MapKeyConvert to specify a named converter to be used with the corresponding mapped attribute key column.


Annotation Elements

Table 2-31 describes this annotation's elements.

Table 2-31 @MapKeyConvert Annotation Elements

Annotation Element Description Default

value

(Optional) Name of the converter to use:

  • serialized

  • class-instance

  • none

  • custom converter

none



Usage

Use @MapKeyConvert to convert the key value used in a @MapKeyColumn to have a different type or value than the database column.

The @MapKeyConvert annotation has the following reserved names:

If you do not use one of these reserved names, you must define a custom converter, using the @Converter annotation.


Examples

Example 2-56 shows using a @MapKeyConvert annotation to apply a converter to a map's key.

Example 2-56 Using @MapKeyConvert Annotation

@Entity
public class Entity
 …
    @ElementCollection
    @MapKeyColumn(name=”BANK”)
    @Column(name=”ACCOUNT”)
    @Convert(”Long2String”)
    @MapKeyConvert(”CreditLine”)
    public Map<String,Long> getCreditLines() {
        return creditLines;
    }

Example 2-57 shows how to use the <map-key-convert> element in the eclipselink-orm.xml file.

Example 2-57 Using <map-key-convert> XML

<element-collection name="creditLines">
  <map-key-convert>CreditLine</map-key-convert>
  <map-key-column name="BANK"/>
  <column name="ACCOUNT"/>
  <convert>Long2String</convert>
  <object-type-converter name="CreditLine">
    <conversion-value data-value="RBC" object-value="RoyalBank"/>
    <conversion-value data-value="CIBC" object-value="CanadianImperial"/>
    <conversion-value data-value="SB" object-value="Scotiabank"/>
    <conversion-value data-value="TD" object-value="TorontoDominion"/>
  </object-type-converter>
  <type-converter name="Long2String" data-type="String" object-type="Long"/>
  <collection-table name="EMP_CREDITLINES">
    <join-column name="EMP_ID"/>
  </collection-table>
</element-collection>


See Also

For more information, see:


@Multitenant

The @Multitenant annotation specifies that a given entity is shared among multiple tenants of an application. The multitenant type specifies how the data for these entities are to be stored on the database for each tenant. Multitenancy can be specified at the entity or mapped superclass level.


Annotation Elements

Table 2-32 describes this annotation's elements.

Table 2-32 @Multitenant Annotation Elements

Annotation Element Description Default

boolean includeCriteria

Indicates if the database requires the tenant criteria to be added to the SELECT, UPDATE, and DELETE queries.

true

MultitenantType value

Specifies the multitenant strategy to use: SINGLE_TABLE, TABLE_PER_TENANT, or VPD.

SINGLE_TABLE



Usage

To use the @Multitenant annotation, include the annotation with an @Entity or @MappedSuperclass annotation. For example:

@Entity
@Multitenant
...
public class Employee() {
  ...
}
 

Three types of multitenancy are available:

Example

Example 2-58 shows a simple example of a @Multitenant annotation. In this example, the Player entity has rows for multiple tenants stored in its default PLAYER table and that the default TENANT_ID column is used as a discriminator along with the default context property eclipselink.tenant-id.

Example 2-58 Minimal @Multitenant Annotation

@Entity
@Multitenant
public class Player  {
}

To have your application use a shared EntityManagerFactory and have the EntityManager be tenant specific, your runtime code might be:

Map<String, Object> emProperties = new HashMap<String, Object>();

emProperties.set("eclipselink.tenant-id", "HTHL");

EntityManager em = emf.createEntityManager(emProperties);

Review "Single-Table Multitenancy", "Table-Per-Tenanat Multitenancy", and "VPD Multitenancy" for more detailed examples.


Single-Table Multitenancy

The SINGLE_TABLE multitenant type specifies that any table to which an entity or mapped superclass maps can include rows for multiple tenants. Access to tenant-specific rows is restricted to the tenant.

Tenant-specific rows are associated with the tenant by using tenant discriminator columns. The discriminator columns are used with application context values to limit what a persistence context can access.

The results of queries on the mapped tables are limited to the tenant discriminator value(s) provided as property values. This applies to all insert, update, and delete operations on the table. When multitenant metadata is applied at the mapped superclass level, it is applied to all subentities unless they specify their own multitenant metadata.


NoteNote:

In the context of single-table multitenancy, ”single-table” means multiple tenants can share a single table, and each tenant's data is distinguished from other tenants' data via the discriminator column(s). It is possible to use multiple tables with single-table multitenancy; but in that case, an entity's persisted data is stored in multiple tables (Table and SecondaryTable), and multiple tenants can share all the tables.


For more information how to use tenant discriminator columns to configure single-table multitenancy, see "@TenantDiscriminatorColumn".


Examples

The following example uses @Multitenant, @TenantDiscriminatorColumn, and a context property to define single-table multitenancy on an entity:

Example 2-59 Example Using @Multitenant

@Entity 
@Table(name=”EMP”) 
@Multitenant(SINGLE_TABLE) 
@TenantDiscriminatorColumn(name = ”TENANT_ID”, 
   contextProperty = "employee-tenant.id")

The following example uses the <multitenant> element to specify a minimal single-table multitenancy. SINGLE_TABLE is the default value and therefore does not have to be specified.

Example 2-60 Example Using <multitenant>

<entity class="model.Employee">
  <multitenant/>
  <table name="EMP"/>
  ...
</entity>

Table-Per-Tenanat Multitenancy

The TABLE_PER_TENANT multitenant type specifies that the table(s) (Table and SecondaryTable) for an entity are tenant-specific tables based on the tenant context.. Access to these tables is restricted to the specified tenant. Relationships within an entity that use a join or collection table are also assumed to exist within that context.

As with other multitenant types, table-per-tenant multitenancy can be specified at the entity or mapped superclass level. At the entity level, a tenant context property must be provided on each entity manager after a transaction has started.

Table-per-tenant entities can be mixed with other multitenant-type entities within the same persistence unit.

All read, insert, update, and delete operations for the tenant apply only to the tenant's table(s).

Tenants share the same server session by default. The table-per-tenant identifier must be set or updated for each entity manager. ID generation is assumed to be unique across all the tenants in a table-per-tenant strategy.

To configure table-per-tenant multitenancy, you must specify:


Examples

The following example shows the @Multitenant annotation used to define table-per-tenant multitenancy on an entity. @TenantTableDiscriminator(SCHEMA) specifies that the discriminator table is identified by schema.

Example 2-61 Example Using @Multitenant with @TenantTableDiscriminator

@Entity
@Table(name=”EMP”)
@Multitenant(TABLE_PER_TENANT)
@TenantTableDiscriminator(SCHEMA)
public class Employee {
    ...
}

The following example shows the <multitenant> element and the <tenant-table-discriminator> elements used to define a minimal table-per-tenant multitenancy.

Example 2-62 Example Using <multitenant> with <tenant-table-discriminator>

<entity class="Employee">
  <multitenant type="TABLE_PER_TENANT">
    <tenant-table-discriminator type="SCHEMA"/>
  </multitenant>
  <table name="EMP">
  ...
</entity>

VPD Multitenancy

The VPD (Virtual Private Database) multitanancy type specifies that the database handles the tenant filtering on all SELECT, UPDATE and DELETE queries. To use this type, the platform used with the persistence unit must support VPD.

To use EclipseLink VPD multitenancy, you must first configure VPD in the database and then specify multitenancy on the entity or mapped superclass, using @Multitenant and @TenantDiscriminatorColumn:


Examples

Example 2-63 shows VPD multitenancy defined on an entity. As noted above, VPD in the database must also be configured to enable VPD multitenancy. In this case, the VPD database was configured to use the USER_ID column to restrict access to specified rows by specified clients. Therefore, USER_ID is also specified as the tenant discriminator column for the EclipseLink multitenant operations.

Example 2-63 Example Using @Multitenant(VPD)

The following example shows

@Entity
@Multitenant(VPD)
@TenantDiscriminatorColumn(name = "USER_ID", contextProperty = "tenant.id")
@Cacheable(false)
 
public class Task implements Serializable {
...
...

The following example shows...

Example 2-64 Example Using <multitenant>

<entity class="model.Employee"> 
  <multitenant type="VPD">
    <tenant-discriminator-column name="USER_ID" context-property="tenant.id"/> 
  </multitenant>
  <table name="EMPLOYEE"/>
  ...
</entity>


See Also


@Mutable

Use @Mutable on a @Basic mapping to specify if the value of a complex field type can be changed (or not changed) instead of being replaced. Mutable mappings may affect the performance of change tracking; attribute change tracking can only be weaved with non-mutable mappings.


Annotation Elements

Table 2-33 describes this annotation's elements.

Table 2-33 @Mutable Annotation Elements

Annotation Element Description Default

boolean value

(Optional) Specifies if the mapping is mutable.

true



Usage

Most basic types (such as int, long, float, double, String, and BigDecimal) are not mutable.

By default, Date and Calendar types are assumed to be not mutable. To make these types mutable, use the @Mutable annotation. You can also use the global persistence property eclipselink.temporal.mutable to set the mappings as mutable.

By default, serialized types are assumed to be mutable. You can set the @Mutable annotation to false to make these types not mutable.

You can also configure mutable mappings for Date and Calendar fields in the persistence unit in the persistence.xml file.


Examples

Example 2-65 shows how to use the @Mutable annotation to specify Employee field hireDate.

Example 2-65 Using @Mutable Annotation

@Entity
public class Employee implements Serializable {

    ...

    @Temporal(DATE)
    @Mutable
    public Calendar getHireDate() {
        return hireDate;
    }

..
}

Example 2-66 shows how to configure mutable mappings in the persistence unit persistence.xml file or by importing a property map.

Example 2-66 Specifying Mutable Mappings in persistence.xml

Using persistence.xml file:

<property name="eclipselink.temporal.mutable" value="true"/>

Using property map:

import org.eclipse.persistence.config.PersistenceUnitProperties;
propertiesMap.put(PersistenceUnitProperties.TEMPORAL_MUTABLE, "false");


See Also

For more information, see:


@NamedPLSQLStoredFunctionQueries

Use the @NamedPLSQLStoredFunctionQueries annotation to define multiple NamedPLSQLStoredFunctionQuery items.


Annotation Elements

Table 2-34 describes this annotation's elements.

Table 2-34 @NamedPLSQLStoredFunctionQueries Annotation Elements

Annotation Element Description Default

NamedStoredFunctionQuery[]

(Required) An array of named stored procedure query




See Also

For more information, see:


@NamedPLSQLStoredFunctionQuery

Use the @NamedPLSQLStoredFunctionQuery annotation to define queries that call Oracle PLSQL stored functions as named queries


Annotation Elements

Table 2-36 describes this annotation's elements.

Table 2-35 @NamedPLSQLStoredFunctionQuery Annotation Elements

Annotation Element Description Default

functionName

(Required) The name of the stored function


name

(Required) The unique name that references this stored function query


returnParamter

(Required) The return value of the stored function


hints

(Optional) Query hints


parameters

(Optional) The parameters for the stored function


resultSetMapping

(Optional) The name of the SQLResultMapping




Usage

This annotation adds support for complex PLSQL types such as RECORD and TABLE, that are not accessible from JDBC.

You can specify @NamedPLSQLStoredFunctionQuery on an Entity or MappedSuperclass.


Examples

Example 2-67 shows how to use this annotation.

Example 2-67 Using @NamedPLSQLStoredFunctionQuery Annotation

@NamedPLSQLStoredFunctionQuery(
    name="getEmployee", 
    functionName="EMP_PKG.GET_EMP",
    returnParameter=@PLSQLParameter(
        name="RESULT", 
        databaseType="EMP_PKG.EMP_TABLE"
    )
)
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME", "L_NAME", "SALARY"})
@PLSQLRecord(
    name="EMP_PKG.EMP_REC", 
    compatibleType="EMP_TYPE",
    javaType=Employee.class,
    fields={
        @PLSQLParameter(name="F_NAME"), 
        @PLSQLParameter(name="L_NAME"),
        @PLSQLParameter(
            name="SALARY", 
            databaseType="NUMERIC_TYPE"
        )
    }
)

public class Employee { ...}


See Also

For more information, see:


@NamedPLSQLStoredProcedureQueries

Use the @NamedPLSQLStoredProcedureQueries annotation to define multiple NamedPLSQLStoredProcedureQuery items.


Annotation Elements

Table 2-36 describes this annotation's elements.

Table 2-36 @NamedPLSQLStoredProcedureQueries Annotation Elements

Annotation Element Description Default

value

(Required) An array of named stored procedure query




Examples

Example 2-68 shows how to use this annotation.

Example 2-68 Using @NamedPLSQLStoredProcedureQueries Annotation

@NamedPLSQLStoredProcedureQueries({ 
    @NamedPLSQLStoredProcedureQuery(name="getEmployee", 
    functionName="EMP_PKG.GET_EMP", 
    parameters={ @PLSQLParameter( name="EMP_OUT", direction=:Direction.OUT, databaseType="EMP_PKG.EMP_REC") } )
    })


See Also

For more information, see:


@NamedPLSQLStoredProcedureQuery

Use the @NamedPLSQLStoredProcedureQuery annotation to define queries that call Oracle PLSQL stored procedures as named queries.


Annotation Elements

Table 2-37 describes this annotation's elements.

Table 2-37 @NamedPLSQLStoredProcedureQuery Annotation Elements

Annotation Element Description Default

procedureName

(Required) The name of the stored procedure


name

(Required) The unique name that references this stored procedure query


resultClass

(Optional) The class of the result


hints

(Optional) Query hints


parameters

(Optional) The parameters for the stored procedure


resultSetMapping

(Optional) The name of the SQLResultMapping




Usage

This annotation adds support for complex PLSQL types such as RECORD and TABLE, that are not accessible from JDBC.

You can specify @NamedPLSQLStoredProcedureQuery on an Entity, Embeddable, or MappedSuperclass.


Examples

Example 2-69 shows how to use this annotation.

Example 2-69 Using @NamedPLSQLStoredProcedureQuery Annotation

@NamedPLSQLStoredProcedureQuery(
    name="getEmployee",
    procedureName="MyStoredProcedure",
    functionName="EMP_PKG.GET_EMP", 
    parameters={
        @PLSQLParameter(
            name="EMP_OUT", 
            direction=Direction.OUT,
            databaseType="EMP_PKG.EMP_REC"
        )
    }
)
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME", "L_NAME", "SALARY"})
@OracleObject(
    name="EMP_PKG.EMP_REC",
    compatibleType="EMP_TYPE",
    javaType=Employee.class,
    fields={
        @PLSQLParameter(name="F_NAME"),
        @PLSQLParameter(name="L_NAME"),
        @PLSQLParameter(
            name="SALARY",
            databaseType="NUMERIC_TYPE"
        )
    }
)
 
public class Employee { ...}


See Also

For more information, see:


@NamedStoredFunctionQueries

Use the @NamedStoredFunctionQueries annotation to define multiple NamedStoredFunctionQuery items.


Annotation Elements

Table 2-38 describes this annotation's elements.

Table 2-38 @NamedStoredFunctionQueries Annotation Elements

Annotation Element Description Default

NamedStoredFunctionQuery[]

(Required) An array of named stored procedure query




Examples

Example 2-70 shows how to use this annotation.

Example 2-70 Using @NamedStoredFunctionQueries Annotation

@NamedStoredFunctionQueries{(
    @NamedStoredFunctionQuery(
        name="StoredFunction_In",
        functionName="StoredFunction_In",
        parameters={
            @StoredProcedureParameter(direction=IN, name="P_IN", queryParameter="P_IN", type=Long.class)
        },
        returnParameter=@StoredProcedureParameter(queryParameter="RETURN", type=Long.class)
    )
)}

To define multiple named stored procedures in the eclipselink-orm.xml file, create a list of multiple <named-stored-function_query> elements.


See Also

For more information, see:


@NamedStoredFunctionQuery

Use @NamedStoredFunctionQuery to define queries that call stored functions as named queries.


Annotation Elements

Table 2-39 describes this annotation's elements.

Table 2-39 @NamedStoredFunctionQuery Annotation Elements

Annotation Element Description Default

functionName

(Required) The name of the stored function


name

(Required) The unique name that references this stored function query


returnParamter

(Required) The return value of the stored function


callByIndex

(Optional) Specifies if the stored function should be called by index or by name.

  • If by index, the parameters must be defined in the same order as the procedure on the database.

  • If by name, you must use the database platform support naming procedure parameters.

false

hints

(Optional) Query hints


parameters

(Optional) The parameters for the stored function


resultSetMapping

(Optional) The name of the SQLResultMapping




Usage

You can specify @NamedStoredFunctionQuery on an Entity or MappedSuperclass.


Examples

Example 2-71 shows how to use this annotation.

Example 2-71 Using @NamedStoredFunctionQuery Annotation

@Entity
@Table(name="CMP3_ADDRESS")
 
@NamedStoredFunctionQuery(
  name="StoredFunction_In",
  functionName="StoredFunction_In",
  parameters={
    @StoredProcedureParameter(direction=IN, name="P_IN", queryParameter="P_IN", type=Long.class)
    },
  returnParameter=@StoredProcedureParameter(queryParameter="RETURN", type=Long.class)
  )
public class Address implements Serializable {
...
}

Example 2-72 shows how to use the <named-stored-function-query> element in the eclipselink-orm.xml file.

Example 2-72 Using <named-stored-function-query> XML

<named-stored-function-query name="StoredFunction_In" procedure-name="StoredFunction_In">
    <parameter direction="IN" name="P_IN" query-parameter="P_IN" type="Long"/>
</named-stored-function-query>


See Also

For more information, see:


@NamedStoredProcedureQueries

Use the @NamedStoredProcedureQueries annotation to define multiple NamedStoredProcedureQuery items.


Annotation Elements

Table 2-40 describes this annotation's elements.

Table 2-40 @NamedStoredProcedureQueries Annotation Elements

Annotation Element Description Default

value

(Required) An array of named stored procedure query




Examples

Example 2-73 shows how to use this annotation.

Example 2-73 Using @NamedStoredProcedureQueries Annotation

@Entity
@Table(name="EMPLOYEE")
@NamedStoredProcedureQueries({
  @NamedStoredProcedureQuery(
    name="ReadEmployeeInOut",
     resultClass=org.eclipse.persistence.testing.models.jpa.customfeatures.Employee.class,
    procedureName="Read_Employee_InOut",
    parameters={
      @StoredProcedureParameter(direction=IN_OUT, name="employee_id_v", queryParameter="ID", type=Integer.class),
      @StoredProcedureParameter(direction=OUT, name="nchar_v", queryParameter="NCHARTYPE", type=Character.class)}
    ),
    @NamedStoredProcedureQuery(
      name="ReadEmployeeCursor",
      resultClass=org.eclipse.persistence.testing.models.jpa.customfeatures.Employee.class,
      procedureName="Read_Employee_Cursor",
      parameters={
        @StoredProcedureParameter(direction=IN, name="employee_id_v", queryParameter="ID", type=Integer.class),
        @StoredProcedureParameter(direction=OUT_CURSOR, queryParameter="RESULT_CURSOR")})
})
public class Employee implements Serializable {

To define multiple named stored procedure queries in the eclipselink-orm.xml file, simply create a list of multiple <named-stored-procedure_query> elements.


See Also

For more information, see:


@NamedStoredProcedureQuery

Use the @NamedStoredProcedureQuery annotation to define queries that call stored procedures as named queries.


Annotation Elements

Table 2-41 describes this annotation's elements.

Table 2-41 @NamedStoredProcedureQuery Annotation Elements

Annotation Element Description Default

name

(Required) Unique name that references this stored procedure query


procedureName

(Required) Name of the stored procedure


callByIndex

(Optional) Specifies if the stored procedure should be called by name.

  • If true, the StoredProcedureParameters must be defined in the same order as the procedure on the database.

  • If false, the database platform must support naming procedure parameters.

false

hints

(Optional) An array of query hints


multipleResultSets

(Optional) Specifies if the stored procedure returns multiple result sets.

This applies only for databases that support multiple result sets from stored procedures.

false

parameters

(Optional) An array of parameters for the stored procedure


resultClass

(Optional) The class of the result

void.class

resultSetMapping

(Optional) Name of the SQLResultMapping


returnsResultSet

(Optional) Specifies if the stored procedure retainers a result set.

This applies only for databases that support result sets from stored procedures.

false



Usage

You can specify @NamedStoredProcedureQuery on an Entity or MappedSuper class.


Examples

Example 2-74 shows how to use @NamedStoredProcedureQuery to define a stored procedure.

Example 2-74 Using @NamedStoredProcedureQuery Annotation

@NamedStoredProcedureQuery(name="findAllEmployees", procedureName="EMP_READ_ALL", resultClass=Employee.class, parameters={
    @StoredProcedureParameter(queryParameter="result", name="RESULT_CURSOR", direction=Direction.OUT_CURSOR})
@Entity
public class Employee {
 ...
}

Example 2-75 shows how to use the <named-stored-procedure-query> element in the eclipselink-orm.xml file.

Example 2-75 Using <named-stored-procedure-query> XML

<named-stored-procedure-query name="SProcXMLInOut" result-class="Address" procedure-name="SProc_Read_XMLInOut">
    <parameter direction="IN_OUT" name="address_id_v" query-parameter="ADDRESS_ID" type="Long"/>
    <parameter direction="OUT" name="street_v" query-parameter="STREET" type="String"/>
</named-stored-procedure-query>


See Also

For more information, see:


@Noncacheable

Use @Noncacheable to configure caching behavior for relationships. If used on a relationship, that relationship will not be cached, even though the parent Entity may be cached.


Annotation Elements

There are no elements for this annotation.


Usage

Each time EclipseLink retrieves the Entity, the relationship will be reloaded from the datasource. This may be useful for situations where caching of relationships is not desired or when using different EclipseLink cache types and having cached references extends the cache lifetime of related Entities using a different caching scheme. For instance Entity A references Entity B, Entity A is Full and Entity B is Weak. Without removing the caching of the relationsip the Entity B's cache effectively become Full.


Examples

Example 2-76 shows how to use @Noncacheable to create a protected cache.

Example 2-76 Using @Noncacheable Annotation

@Entity
@Cache(
  isolation=CacheIsolationType.PROTECTED
)
public class Employee {
  @Id
  private long id;
  ...
  @OneToMany(mappedBy="manager")
  @Noncacheable
  private List<Employee> managedEmployees;
  ...
}

Example 2-77 shows using the <noncacheable> XML element in the eclipselink-orm.xml file.

Example 2-77 Using <noncacheable> XML

<?xml version="1.0"?>
<entity-mappings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd"
    version="2.4">
    <entity name="Employee" class="org.acme.Employee" access="FIELD">
        <cache isolation="PROTECTED"/>
        <attributes>
            <id name= "id"/>
            <one-to-many name="managedEmployees" mapped-by="manager">
                <noncacheable/>
            </one-to-many>
        </attributes>
    </entity>
</entity-mappings


See Also

For more information, see:


@NoSql

Use @NoSql to specify a non-relational (that is, no SQL) data source. EclipseLink can map non-relational data to objects and access that data through JPA.


Annotation Elements

Table 2-42 describes this annotation's elements.

Table 2-42 @NoSql Annotation Elements

Annotation Element Description Default

dataType

The name of the entities structure. The purpose of the dataType depends on the NoSQL platform used:

  • For MongoDB, it is the collection name that the JSON documents are stored to.

  • For Oracle NoSQL, it is the first part of the major key value.

  • For XML files, it is the file name. and XML messaging, use XML.


dataFormat

(Optional) The type structure (data format) in which the data is stored within the database:

  • INDEXED – Maps a class to an array of values.

  • MAPPED – Maps a class to a set of nested key/value pairs, a value can be an embedded map or list.

    Use to map to key/value stores, JSON databases, and other structured data systems.

  • XML – Maps a class to an XML document.

    Use with XML data-stores, XML files, XML messaging systems, and other XML systems.

XML



Usage

The dataFormat depends on the NoSQL platform used:

Supported Datasources

EclipseLink supports several NoSQL and EIS platforms, as well as generic NoSQL and EIS datasources through the JavaEE Connector Architecture CCI (Common Client Interface) API. You can also define your own EISPlatform subclass and JCA adapter

EclipseLink supports the following datasources:


Examples

Example 2-78 shows using @NoSql with an XML data source.

Example 2-78 Using @NoSql Annotation with XML

@Entity
@NoSql(dataType="order")
public class Order {
  @Id
  @GeneratedValue
  @Field(name="@id")
  private long id;
  @Basic
  @Field(name="@description")
  private String description;
  @Embedded
  @Field(name="delivery-address")
  private Address deliveryAddress
  @ElementCollection
  @Field(name="orderLines/order-line")
  private List<OrderLine> orderLines;
  @ManyToOne
  @JoinField(name="customer-id")
  private Customer customer;
}
 
@Embeddable
@NoSql
public class OrderLine {
    @Field(name="@line-number")
    private int lineNumber;
    @Field(name="@item-name")
    private String itemName;
    @Field(name="@quantity")
    private int quantity;  
}

This would produce the following XML data:

<order id="4F99702B271B1948027FAF06" description="widget order">
  <deliveryAddress street="1712 Hasting Street" city="Ottawa" province="ON" postalCode="L5J1H5"/>
  <order-lines>
      <order-line lineNumber="1" itemName="widget A" quantity="5"/>
      <order-line lineNumber="2" itemName="widget B" quantity="1"/>
      <order-line lineNumber="3" itemName="widget C" quantity="2"/>
  <order-lines>
  <customer-id>4F99702B271B1948027FAF08</customer-id>
<order>

Example 2-79 shows using @NoSql with a JSON data source.

Example 2-79 Using @NoSql Annotation with JSON

@Entity
@NoSql(dataType="orders", dataFormat=DataFormatType.MAPPED)
public class Order {
  @Id
  @GeneratedValue
  @Field(name="_id")
  private long id;
  @Basic
  @Field(name="description")
  private String description;
  @Embedded
  @Field(name="deliveryAddress")
  private Address deliveryAddress
  @ElementCollection
  @Field(name="orderLines")
  private List<OrderLine> orderLines;
  @ManyToOne
  @JoinField(name="customerId")
  private Customer customer;
}
 
@Embeddable
@NoSql(dataFormat=DataFormatType.MAPPED)
public class OrderLine {
    @Field(name="lineNumber")
    private int lineNumber;
    @Field(name="itemName")
    private String itemName;
    @Field(name="quantity")
    private int quantity;  
}

This would produce the following JSON document:

{
  "_id": "4F99702B271B1948027FAF06",
  "description": "widget order",
  "deliveryAddress": {
      "street": "1712 Hasting Street",
      "city": "Ottawa",
      "province": "ON",
      "postalCode": "L5J1H5",
  },
  "orderLines": [
      {"lineNumber": "1", "itemName": "widget A", "quantity": "5"},
      {"lineNumber": "2", "itemName": "widget B", "quantity": "1"},
      {"lineNumber": "3", "itemName": "widget C", "quantity": "2"}
  ],
  "customerId": "4F99702B271B1948027FAF08",
}


See Also

For more information, see:


@ObjectTypeConverter

The @ObjectTypeConverter annotation specifies an org.eclipse.persistence.mappings.converters.ObjectTypeConverter that converts a fixed number of database data value(s) to Java object value(s) during the reading and writing of a mapped attribute.


Annotation Elements

Table 2-43 describes this annotation's elements.

Table 2-43 @ObjectTypeConverter Annotation Elements

Annotation Element Description Default

name

Set this attribute to the String name for your converter. Ensure that this name is unique across the persistence unit.

none

dataType

(Optional) Set this attribute to the type stored in the database.

void.classFoot 

objectType

(Optional) Set the value of this attribute to the type stored on the entity.

void.classFootref 1

conversionValues

Set the value of this attribute to the array of conversion values (instances of ConversionValue: String objectValue and String dataValue).

none

defaultObjectValue

Set the value of this attribute to the default object value. Note that this argument is for dealing with legacy data if the data value is missing.

Empty String


Footnote The default is inferred from the type of the persistence field or property.


Usage

EclipseLink also includes @TypeConverter and @StructConverter converters.


Examples

Example 2-80 shows how to use the @ObjectTypeConverter annotation to specify object converters for the gender field.

Example 2-80 Using the @ObjectTypeConverter Annotation

public class Employee implements Serializable{
     ...
     @ObjectTypeConverter (
         name="genderConverter",
         dataType=java.lang.String.class,
         objectType=java.lang.String.class,
         conversionValues={
             @ConversionValue(dataValue="F", objectValue="Female"),
             @ConversionValue(dataValue="M", objectValue="Male")}
     )
     @Convert("genderConverter")
     public String getGender() {
         return gender;
     }
     ...
 }

You can use the <object-type-converter> element in the deployment descriptor as an alternative to using the @ObjectTypeConverter annotation in the source code, as shown in Example 2-81.

Example 2-81 Using <object-type-converter> XML

<object-type-converter name="gender-converter" object-type="model.Gender"     data-type="java.lang.String">
    <conversion-value object-value="Male" data-value="M" />
    <conversion-value object-value="Female" data-value="F" />
</object-type-converter>


See Also

For more information, see:


@ObjectTypeConverters

Use @ObjectTypeConverters to define multiple ObjectTypeConverter items.


Annotation Elements

Table 2-44 describes this annotation's elements.

Table 2-44 @ObjectTypeConverters Annotation Elements

Annotation Element Description Default

ObjectTypeConverter

(Required) An array of @ObjectTypeConverter




Examples

Example 2-82 shows how to use this annotation.

Example 2-82 Using @ObjectTypeConverters Annotation

@Entity(name="Employee")
@Table(name="CMP3_FA_EMPLOYEE")
@ObjectTypeConverters({
  @ObjectTypeConverter(
    name="sex",
    dataType=String.class,
    objectType=org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Employee.Gender.class,
    conversionValues={
      @ConversionValue(dataValue="F", objectValue="Female"),
      @ConversionValue(dataValue="M", objectValue="Male")
    }
  )
})

To define multiple object type converts in the eclipselink-orm.xml file, simply create a list of multiple <object-type-converter> elements.


See Also

For more information, see:


@OptimisticLocking

Use @OptimisticLocking to specify the type of optimistic locking EclipseLink should use when updating or deleting entities.


Annotation Elements

Table 2-45 describes this annotation's elements.

Table 2-45 @OptimisticLocking Annotation Elements

Annotation Element Description Default

cascade

(Optional) Specify where the optimistic locking policy should cascade lock. When changing private owned and delete orphan object, EclipseLink will update the version.

This element is currently only supported with VERSION_COLUMN locking.

false

selectedColumns

(Optional) Specify a list of columns that will be optimistically locked.

This element is required when type=SELECTED_COLUMNS.


type

(Optional) The type of optimistic locking policy to use:

  • ALL_COLUMNS – EclipseLink compares every field in the table with the WHERE clause, when performing and update or delete operation.

  • CHANGED_COLUMNS – EclipseLink compares only the changed fields in the WHERE clause when performing an update.

  • SELECTED_COLUMNS – EclipseLink compares the selected field in the WHERE clause when performing and update or delete operation on the SelectedColumns.

  • VERSION_COLUMN – EclipseLink compares a single version number in the WHERE clause when performing an update.

VERSION_COLUMN



Usage

You can specify @OptimisticLocking on an Entity or MappedSuperclass.


Examples

Example 2-83 shows how to use the @OptimisticLocking annotation for all columns

Example 2-83 Using @OptimisticLocking Annotation

@Table(name = "EMPLOYEES")
  @OptimisticLocking(type=OptimisticLockingType.ALL_COLUMNS)
  public class Employee implements Serializable {
      ...
  }

Example 2-83 shows how to use the <optimistic-locking> element in the eclipselink-orm.xml file for a single column.

Example 2-84 Using <optimistic-locking> XML

<entity name="Employee" class="my.Employee" access="PROPERTY" change-tracking="DEFERRED">
...
    <optimistic-locking type="SELECTED_COLUMNS" cascade="false">
      <selected-column name="id"/>
      <selected-column name="firstName"/>
    </optimistic-locking>
...
</entity>


See Also

For more information, see:


@OracleArray

Use the @OracleArray annotation to define an Oracle database VARRAY type, which you can use within PLSQL procedure calls.


Annotation Elements

Table 2-46 describes the annotation's elements.

Table 2-46 @OracleArray Annotation Elements

Element Description Default

name

(Required) The name of the VARRAY in the database


nestedType

(Required) The name of the database type that the VARRAY holds

VARCHAR_TYPE

javaType

(Optional) The Java Collection class to which the VARRAY is mapped

ArrayList



Examples

Example 2-85 shows how to use the @OracleArray annotation to define a VARRAY type.

Example 2-85 Using the @OracleArray Annoation

@NamedPLSQLStoredFunctionQuery(
name="getEmployee", 
functionName="EMP_PKG.GET_EMP",
parameters={
   @PLSQLParameter(
     name="EMP_OUT",
     direction=Direction.OUT,
     databaseType="EMP_PKG.EMP_REC"
     )
   }
)
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME",
"L_NAME","SALARY"})
@OracleArray(
   name="EMP_PKG.EMP_REC",
   nestedType=VARCHAR_TYPE
   javaType=Employee.class,
)
public class Employee{...}


See Also

For more information, see:


@OracleArrays

Use the @OracleArrays annotation to define multiple VARRAY types.


Annotation Elements

Table 2-47 describes the annotation's elements.

Table 2-47 @OracleArrays Attribute Elements

Element Description Default

value

(Required) An array of Oracle VARRAY types




Examples

See "@OracleArray" for an example of how to use this annotation.


See Also

For more information, see:


@OracleObject

Use the @OracleObject annotation to define an Oracle database OBJECT type, which you can use within PLSQL procedure calls.


Annotation Elements

Table 2-48 describes the annotation's elements.

Table 2-48 @OracleObject Annotation Elements

Element Description Default

name

(Required) The name of the OBJECT type in the database


javaType

(Optional) The Java type to which you want to map the OBJECT type. This class must be mapped using an @STRUCT annotation

void

fields

(Required) Defines the parameter fields in the record type




Examples

Example 2-86 shows how to use the @OracleObject annotation to define an Oracle OBJECT type.

Example 2-86 Using the @OracleObject Annotation

@NamedPLSQLStoredFunctionQuery(
name="getEmployee",
functionName="EMP_PKG.GET_EMP",
parameters={
   @PLSQLParameter(
     name="EMP_OUT",
     direction=Direction.OUT,
     databaseType="EMP_PKG.EMP_REC"
     )
   }
)
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME",
"L_NAME","SALARY"})
@OracleObject(
   name="EMP_PKG.EMP_REC",
   javaType=Employee.class,
   fields={
     @PLSQLParameter(name="F_NAME"),
     @PLSQLParameter(name="L_NAME"),
     @PLSQLParameter(
      name="SALARY",
      databaseType="NUMERIC_TYPE"
     )
   }
)
public class Employee{...}


See Also

For more information, see:


@OracleObjects

Use the @OracleObjects annotation to define multiple Oracle OBJECT types.


Annotation Elements

Table 2-49 describes the annotation's elements.

Table 2-49 @OracleObjects Annotation Elements

Element Description Default

value

(Required) An array of Oracle OBJECT types




Examples

See "@OracleObject" for an example of how to use this annotation.


See Also

For more information, see:


@OrderCorrection

Use @OrderCorrection to specify a strategy to use if the order list read from the database is invalid (for example, it has nulls, duplicates, negative values, or values greater than or equal to the list size).

To be valid, an order list of n elements must be {0, 1,..., n-1}


Annotation Elements

Table 2-50 describes this annotation's elements.

Table 2-50 @OrderCorrection Annotation Elements

Annotation Element Description Default

value

(Optional) Specify a strategy to use if the order list read from the database is invalid:

  • EXCEPTION

  • READ

  • READ_WRITE

READ_WRITE



Usage

When using @OrderCorrection, you can specify how EclipseLink should handle invalid list orders:


Examples

Example 2-87 shows how to use this annotation.

Example 2-87 Using @OrderCorrection Annotation

@OrderColumn(name="ORDER_COLUMN")
@OrderCorrection(EXCEPTION)
List<String> designations;

Example 2-88 shows how to use this extension in the eclipselink-orm.xml file.

Example 2-88 Using <element-collection> in XML

<element-collection name="designations">
    <order-column name="ORDER_COLUMN" correction-type="EXCEPTION"/>
</element-collection>


See Also

For more information see:


@Partitioned

Use @Partitioned to specify a partitioning policy to use for an Entity or relationship.


Annotation Elements

Table 2-51 describes this annotation's elements.

Table 2-51 @Partitioned Annotation Elements

Annotation Element Description Default

value

(Required) Name of the partitioning policy




Usage

Use partitioning to partition the data for a class across multiple databases or a database cluster (such as Oracle RAC). Partitioning can provide improved scalability by allowing multiple database machines to service requests.

You can specify @Partitioned on an Entity, relationship, query, or session/persistence unit.

Partitioning Policies

To configure data partitioning, use the @Partitioned annotation and one or more partitioning policy annotations. The annotations for defining the different kinds of policies are:

Partitioning policies are globally-named objects in a persistence unit and are reusable across multiple descriptors or queries. This improves the usability of the configuration, specifically with JPA annotations and XML.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, JTA should be used to ensure 2-phase commit of the data. An exclusive connection can also be configured in the EntityManager to ensure only a single node is used for a single transaction.

Clustered Databases and Oracle RAC

Some databases support clustering the database across multiple machines. Oracle RAC allows for a single database to span multiple different server nodes. Oracle RAC also supports table and node partitioning of data. A database cluster allows for any of the data to be accessed from any node in the cluster. However, it is generally it is more efficient to partition the data access to specific nodes, to reduce cross node communication.

EclipseLink partitioning can be used in conjunction with a clustered database to reduce cross node communication, and improve scalability.

To use partitioning with a database cluster to following is required:


Examples

Example 2-89 shows how to partition Employee data by location. The two primary sites, Ottawa and Toronto are each stored on a separate database. All other locations are stored on the default database. Project is range partitioned by its ID, as shown in Example 2-90. Each range of ID values are stored on a different database. The employee/project relationship is an example of a cross partition relationship. To allow the employees and projects to be stored on different databases a union policy is used and the join table is replicated to each database.

Example 2-89 Using Partitioning

@Entity
@IdClass(EmployeePK.class)
@UnionPartitioning(
        name="UnionPartitioningAllNodes",
        replicateWrites=true)
@ValuePartitioning(
        name="ValuePartitioningByLOCATION",
        partitionColumn=@Column(name="LOCATION"),
        unionUnpartitionableQueries=true,
        defaultConnectionPool="default",
        partitions={
            @ValuePartition(connectionPool="node2", value="Ottawa"),
            @ValuePartition(connectionPool="node3", value="Toronto")
        })
@Partitioned("ValuePartitioningByLOCATION")
public class Employee {
    @Id
    @Column(name = "EMP_ID")
    private Integer id;
 
    @Id
    private String location;
    ...
 
    @ManyToMany(cascade = { PERSIST, MERGE })
    @Partitioned("UnionPartitioningAllNodes")
    private Collection<Project> projects;
    ...
}

Example 2-90 Using @RangePartitioning

@Entity
@RangePartitioning(
        name="RangePartitioningByPROJ_ID",
        partitionColumn=@Column(name="PROJ_ID"),
        partitionValueType=Integer.class,
        unionUnpartitionableQueries=true,
        partitions={
            @RangePartition(connectionPool="default", startValue="0", endValue="1000"),
            @RangePartition(connectionPool="node2", startValue="1000", endValue="2000"),
            @RangePartition(connectionPool="node3", startValue="2000")
        })
@Partitioned("RangePartitioningByPROJ_ID")
public class Project {
    @Id
    @Column(name="PROJ_ID")
    private Integer id;
    ...
}


See Also

For more information, see:


@Partitioning

Use @Partitioning to configure a custom PartitioningPolicy.


Annotation Elements

Table 2-52 describes this annotation's elements.

Table 2-52 @Partitioning Annotation Elements

Annotation Element Description Default

name

Name of the partition policy. Names must be unique for the persistence unit.


partitioningClass

(Required) Full package.class name of a subclass of PartitioningPolicy




Usage

Data partitioning allows for an application to scale its data across more than a single database machine. EclipseLink supports data partitioning at the Entity level to allow a different set of entity instances for the same class to be stored in a different physical database or different node within a database cluster. Both regular databases and clustered databases are supported. Data can be partitioned both horizontally and vertically.

Partitioning can be enabled on an entity, a relationship, a query, or a persistence unit.


Examples

Example 2-91 shows a custom partitioning policy.

Example 2-91 Using @Partitioning Annotation

@Entity
@Partitioning(name="order", partitioningClass=OrderPartitioningPolicy.class)
@public class Order {
    ...
}
 
public class OrderPartitioningPolicy extends PartitioningPolicy {
 
    public List<Accessor> getConnectionsForQuery(AbstractSession session, DatabaseQuery query, AbstractRecord arguments) {
        
        List<Accessor> accessors = new ArrayList<Accessor>(1);
        accessors.add(getAccessor(ACMEPool.leastBusy(), session, query, false));
        return accessors;
    }
}


See Also

For more information, see:


@PinnedPartitioning

Use @PinnedPartitionPolicy to pin requests to a single connection pool, allowing for vertical partitioning (that is, having an entity, query, or session always access a single database).


Annotation Elements

Table 2-53 describes this annotation's elements.

Table 2-53 @PinnedPartitioning Annotation Elements

Annotation Element Description Default

connectionPool

Connection pool name to which to pin queries


name

Name of the partition policy. Names must be unique for the persistence unit.




Usage

Partition policies are globally named, to allow reuse. You must also set the partitioning policy with the @Partitioned annotation.

You can specify @PinnedPartitioning on an Entity, relationship, query, or session/persistence unit.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "Using Partitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@PLSQLParameter

Use @PLSQLParameter within a NamedPLSQLStoredProcedureQuery or PLSQLRecord annotation.


Annotation Elements

Table 2-54 describes this annotation's elements.

Table 2-54 @PLSQLParameter Annotation Elements

Annotation Element Description Default

name

(Required) The query parameter name


direction

(Optional) The direction of the stored procedure parameter:

  • IN – Input parameter

  • IN_OUT – Input and output parameters

  • OUT – Output parameter

  • OUT_CURSOR – Output cursor

IN

databaseType

(Optional) Database data type for the parameter. This either one of the type constants defined in OraclePLSQLTypes, or JDBCTypes, or a custom record or table type name.


length

(Optional) Maximum length of the field value


name

(Optional) Stored procedure parameter name


optional

(Optional) Specify if the parameter is required, or optional and defaulted by the procedure.

false

scale

(Optional) Maximum precision value


precision

(Optional) Maximum precision value




Usage

Use the @PLSQLParameter annotation to configure the parameter and type for Oracle PLSQL stored procedures and record types that use extended PLSQL types instead of regular SQL types. They support PLSQL RECORD, TABLE, BOOLEAN and other extend PLSQL types.


Examples

See "@NamedPLSQLStoredProcedureQuery" for an example using the @PLSQLParameter annotation.


See Also

For more information:


@PLSQLRecord

Use @PLSQLRecord to define a database PLSQL RECORD type for use within PLSQL procedures.


Annotation Elements

Table 2-55 describes this annotation's elements.

Table 2-55 @PLSQLRecord Annotation Elements

Annotation Element Description Default

name

(Required) The name of the table in the database


compatibileType

(Required) Name of the database OBJECTYPE that mirror's the record's structure


fields

(Required) The fields in the record type


javaType

(Optional) The class of the object type. You must map this class with the @Struct annotation.




Usage

Oracle PLSQL RECORD types are structured database types. Although JDBC does not provide a mechanism for returning these types, EclipseLink provides support to translate these types into OBJECT types. You must create an OBJECT type on the database to mirror the RECORD type and provide it as the compatibileType in the @PLSQLRecord.

You can then map the RECORD to a Java class, map the Java class as an @Embeddable, use the @Struct annotations to map the Java class to the OBJECT type that mirrors the RECORD type.

You can then call and return the Java class as parameters to the PLSQL stored procedure query.


Examples

Example 2-92 shows how to use this annotation.

Example 2-92 Using @PLSQLRecord Annotation

@NamedPLSQLStoredFunctionQuery(name="getEmployee", functionName="EMP_PKG.GET_EMP",
    returnParameter=@PLSQLParameter(name="RESULT", databaseType="EMP_PKG.EMP_REC"))
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME", "L_NAME", "SALARY"})
@PLSQLRecord(name="EMP_PKG.EMP_REC", compatibleType="EMP_TYPE", javaType=Employee.class,
    fields={@PLSQLParameter(name="F_NAME"), @PLSQLParameter(name="L_NAME"), @PLSQLParameter(name="SALARY", databaseType="NUMERIC_TYPE")})
public class Employee {
 ...
}


See Also

For more information, see:


@PLSQLRecords

Use @PLSQLRecords to define multiple PLSQLRecord.


Annotation Elements

Table 2-56 describes this annotation's elements.

Table 2-56 @PLSQLRecords Annotation Elements

Annotation Element Description Default

value

(Required) An array of named PLSQL records




Examples

See "@PLSQLRecord" for an example of how to use this annotation.


See Also

For more information, see:


@PLSQLTable

Use the @PLSQLTable annotation to define a database PLSQL TABLE type, which you can use within PLSQL procedure calls.


Annotation Elements

Table 2-57 describes this annotation's elements.

Table 2-57 @PLSQLTable Annotation Elements

Element Description Default

name

(Required) The name of the table type in the database


compatibilityType

(Required) The name of the database VARRAY type that mirrors the structure of the table. The table is converted to and from this type so that it can be passed through JDBC.


nestedType

(Required) The type of table, e.g. TABLE of EMP_REC

VARCHAR_TYPE

javaType

(Optional) The Java Collection class to which the VARRAY is mapped. This class can be any valid Collection implementation.

ArrayList

isNestedTable

(Optional) Indicates a non-associative (nested) table. Typically, you use this method when generating a constructor for the collection in PL/SQL; the constructors for associative (VARRAY) arrays and non-associative (nested) tables differ.

false



Examples

Example 2-93 Using the @PLSQLTable Annotation

@Named PLSQLStoredProcedureQuery(
name="getEmployee",
functionName="EMP_PKG.GET_EMP",
parameters={
   @PLSQLParamter(
     name="EMP_OUT",
     direction=Direction.OUT,
     databaseType="EMP_TABLE"
     )
   }
)
@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME",
"L_NAME", "SALARY"})
@PLSQLTable(
   name="EMP_PKG.EMP_TABLE",
   compatibilityType="EMP_VARRAY",
   nestedType="EMP_REC"
)
public class Employee{...}


See Also

For more information, see:


@PLSQLTables

Use the @PLSQLTables annotation to define mutiple PLSQL tables.


Annotation Elements

Table 2-58 describes this annotation's elements.

Table 2-58 @PLSQLTables Annotation Elements

Annotation Description Default

value

(Required) An array of named PLSQL tables




Examples

See "@PLSQLTable" for examples of how to use this annotation.


See Also

For more information, see:


@PrimaryKey

Use @PrimaryKey to allow advanced configuration of the ID.

A validation policy can be given that allows specifying if zero is a valid ID value. The set of primary key columns can also be specified precisely.


Annotation Elements

Table 2-59 describes this annotation's elements.

Table 2-59 @PrimaryKey Annotation Elements

Annotation Element Description Default

cacheKeyType

(Optional) Configures the cache key type to store the object in the cache. This type can be the basic ID value for simple singleton IDs or an optimized CachedId type. This element can take the following values:

  • ID_VALUE – This value can only be used for simple singleton Ids, suchas long/int/String. This is the default for simple singleton IDs.

  • CACHE_ID – Optimized cache key type that allows composite and complex values. This is the default for composite or complex IDs.

  • AUTO – The cache key type is automatically configured depending on what is optimial for the class.

AUTO

columns

(Optional) Directly specifies the primary key columns. This can be used instead of @Id if the primary key includes a non basic field, such as a foreign key, or a inheritance discriminator, embedded, or transformation mapped field.


validation

(Optional) Configures what ID validation is done:

  • NULL – EclipseLink interprets zero values as zero. This permits primary keys to use a value of zero.

  • ZERO (default) – EclipseLink interprets zero as null.

  • NEGATIVE – EclipseLink interprets negative values as null.

  • NONE – EclipseLink does not validate the ID value.

By default 0 is not a valid ID value, this can be used to allow 0 ID values.

ZERO



Usage

By default, EclipseLink interprets zero as null for primitive types that cannot be null (such as int and long), causing zero to be an invalid value for primary keys. You can modify this setting by using the @PrimaryKey annotation to configure an IdValidation for an entity class. Use the eclipselink.id-validation property to configure an IdValidation for the entire persistence unit.

Setting the validation element also affects how EclipseLink generates IDs: new IDs are generated only for IDs that are not valid (null or 0, by default); setting to NONE disables ID generation.


Examples

Example 2-94 shows how to use this annotation.

Example 2-94 Using @PrimaryKey Annotation

@PrimaryKey(validation=IdValidation.ZERO)
public class Employee implements Serializable, Cloneable {
...
}

Example 2-95 shows how to use the <primary-key> element in your eclipselink-orm.xml file.

Example 2-95 Using @<primary-key> XML

<entity name="Employee" class="foo.Employee" access="PROPERTY">
   <primary-key validation="ZERO"/>
...
</entity>


See Also

For more information, see:


@PrivateOwned

Use @PrivateOwned to specify that a relationship is privately owned; target object is a dependent part of the source object and is not referenced by any other object and cannot exist on its own.


Annotation Elements

The @PrivateOwned annotation does not have attributes.


Usage

Using @PrivateOwned causes many operations to be cascaded across the relationship including delete, insert, refresh, and lock (when cascaded). It also ensures that private objects removed from collections are deleted and that objects added are inserted.

You can specify @PrivateOwned on with @OneToOne, @OneToMany and @VariableOneToOne annotations. Private ownership is implied with the @BasicCollection and @BasicMap annotations.

When the referenced object is privately owned, the referenced child object cannot exist without the parent object.

Additional Information

When indicating that a relationship is privately owned, you are specifying the following:

Normally, do not configure privately owned relationships on objects that might be shared. An object should not be the target in more than one relationship if it is the target in a privately owned relationship.


NoteNote:

Referencing a privately owned object may produce undesired effects, as it is the application's responsibility to "clean up" references to the privately owned object.

If the object becomes de-referenced and is deleted, other objects in the cache that continue to reference the deleted object may cause constraint violations, they may resurrect the object (if using cascade persist), or they may simply not reflect what is in the database.



Examples

Example 2-96 shows using @PrivateOwned to specify Employee field phoneNumbers. .

Example 2-96 Using @PrivateOwned Annotation

@Entity
 public class Employee implements Serializable {
   ...
   @OneToMany(cascade=ALL, mappedBy="employee")
   @PrivateOwned
   public Collection<PhoneNumber> getPhoneNumbers() {
      return phoneNumbers;
   }
   ...
 }


See Also

For more information, see:


@Properties

Use @Property to specify a single user-defined property on a mapped attribute or its get/set method. Use the @Properties annotation to wrap multiple properties.

Although not used by EclipseLink, you can specify mapping properties if an application or extension needs to extend EclipseLink metadata.


Annotation Elements

Table 2-60 describes this annotation's elements.

Table 2-60 @Properties Annotation Elements

Annotation Element Description Default

Property

Array of Property elements




Usage

You can specify @Property on a mapped attribute (or its get/set method) within an Entity, MappedSuperclass, or Embeddable class. You can also specify this annotation on an Entity, MappedSuperclass, or Embeddable class.

Properties defined in MappedSuperclass are passed to all inheriting Entities and MappedSuperclasses. In case of a conflict, property values defined directly on a class always override values inherited from a class's parent.

When using an orm.xml mapping file, EclipseLink ignores @Property and @Properties specified in annotations on mapped attributes; annotations on classes are merged with those specified i the orm.xml file, with the latter taking precedence in case of conflicts.


Examples

Example 2-120 shows how to use the @Properties annotation within a @Transformation mapping. Example 2-121 shows how to use the <properties> XML element within the orm.xml file.


See Also

For more information, see:


@Property

Use @Property to specify a single user-defined property on a mapped attribute or its get/set method. Use the @Properties annotation to wrap multiple properties.


Annotation Elements

Table 2-61 describes this annotation's elements.

Table 2-61 @Property Annotation Elements

Annotation Element Description Default

name

(Required) Name of the property


value

(Required) String representation of the property value, converted to an instance of valueType


valueType

(Optional) Property value type, converted to valueType by ConversionManager. This must be a simple type that can be handled by the ConversionManager.

String



Usage

You can specify @Property on a mapped attribute (or its get/set method) within an Entity, MappedSuperclass, or Embeddable class. You can also specify this annotation on an Entity, MappedSuperclass, or Embeddable class.

Properties defined in MappedSuperclass are passed to all inheriting Entities and MappedSuperclasses. In case of a conflict, property values defined directly on a class always override values inherited from a class's parent.

When using an orm.xml mapping file, EclipseLink ignores @Property and @Properties annotations on mapped attributes; annotations on classes are merged with those specified i the orm.xml file, with the latter taking precedence in case of conflicts.


Examples

Example 2-120 shows how to use the @Property annotation within a @Transformation mapping. Example 2-121 shows how to use the <property> XML element within the orm.xml file.


See Also

For more information, see:


@QueryRedirectors

Use @QueryRedirectors to intercept EclipseLink queries for pre- and post-processing, redirection, or performing some side effect such as auditing.


Annotation Elements

Table 2-62 describes this annotation's elements.

Table 2-62 @QueryRedirectors Annotation Elements

Annotation Element Description Default

allQueries

This AllQueries Query Redirector will be applied to any executing object query that does not have a more precise redirector (like the ReadObjectQuery Redirector) or a redirector set directly on the query.

void.class

delete

A Default Delete Object Query Redirector will be applied to any executing DeleteObjectQuery or DeleteAllQuery that does not have a redirector set directly on the query.

void.class

insert

A Default Insert Query Redirector will be applied to any executing InsertObjectQuery that does not have a redirector set directly on the query.

void.class

readAll

A Default ReadAll Query Redirector will be applied to any executing ReadAllQuery that does not have a redirector set directly on the query.

For users executing a JPA Query through the getResultList(), API this is the redirector that will be invoked

void.class

readObject

A Default ReadObject Query Redirector will be applied to any executing ReadObjectQuery that does not have a redirector set directly on the query.

For users executing a JPA Query through the getSingleResult() API or EntityManager.find(), this is the redirector that will be invoked

void.class

report

A Default ReportQuery Redirector will be applied to any executing ReportQuery that does not have a redirector set directly on the query.

For users executing a JPA Query that contains aggregate functions or selects multiple entities this is the redirector that will be invoked

void.class

update

A Default Update Query Redirector will be applied to any executing UpdateObjectQuery or UpdateAllQuery that does not have a redirector set directly on the query. In EclipseLink an UpdateObjectQuery is executed whenever flushing changes to the datasource.

void.class



Usage

Use @QueryRedirectors to extend the standard EclipseLink query functionality.

You can set a QueryRedirector through the Query Hint eclipselink.query.redirector or set as a default Redirector on an Entity.

QueryRedirectors are used when integrating EclipseLink Grid to redirect queries to the Coherence grid.


Examples

Example 2-97 shows how to use this annotation.

Example 2-97 Using @QueryRedirectors Annotation

@QueryRedirectors(
    allQueries=org.queryredirectors.AllQueriesForEntity.class)
@Entity
public class
...


See Also

For more information, see:


@RangePartition

Use @RangePartition to create a specific range partition for a connection pool. Values within the range will be routed to the specified connection pool.


Annotation Elements

Table 2-63 describes this annotation's elements.

Table 2-63 @RangePartition Annotation Elements

Annotation Element Description Default

connectionPool

The connection pool to which to route queries for the specified range


startValue

The String representation of the range start value


endValue

The String representation of the range end value




Examples

See "Using @RangePartitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@RangePartitioning

Use @RangePartitioning to partitions access to a database cluster by a field value from the object (such as the object's ID, location, or tenant).

EclipseLink assigns each server a range of values. All write or read request for objects with a server's value are sent to that specific server. If a query does not include the field as a parameter, then it can either be sent to all server's and unioned, or left to the session's default behavior.


Annotation Elements

Table 2-64 describes this annotation's elements.

Table 2-64 @RangePartitioning Annotation Elements

Annotation Element Description Default

name

(Required) The name of the partition policy; must be unique for the persistence unit.


partitionColumn

(Required) The database column or query parameter to partition queries by. This is the table column name, not the class attribute name. The column value must be included in the query and should normally be part of the object's ID.

This can also be the name of a query parameter. If a query does not contain the field the query will not be partitioned.


partitions

(Required) List of connection pool names to partition across


partitionValueType

The type of the start and end values

String

unionunpartionableQueries

Defines if queries that do not contain the partition field should be sent to every database and have the result unioned.

false



Usage

Partitioning can be enabled on an Entity, relationship, query, or session/persistence unit.

Partition policies are globally named to allow reuse, the partitioning policy must also be set using the @Partitioned annotation to be used.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

Example 2-98 shows how to use the @RangePartitioning annotation

Example 2-98 Using @RangePartitioning Annotation

@Entity
@Table(name="PART_PROJECT")
@RangePartitioning(
  name="RangePartitioningByPROJ_ID",
  partitionColumn=@Column(name="PROJ_ID"),
  partitionValueType=Integer.class,
  unionUnpartitionableQueries=true,
  partitions={
    @RangePartition(connectionPool="default", startValue="0", endValue="1000"),
    @RangePartition(connectionPool="node2", startValue="1000", endValue="2000"),
    @RangePartition(connectionPool="node3", startValue="2000")
  })
@Partitioned("RangePartitioningByPROJ_ID")
public class Project implements Serializable {
...
}

Example 2-98 shows how to use the <range-partitioning> element in the eclipselink-orm.xml file.

Example 2-99 Using <range-partitioning> XML

<entity name="Project" class="Project" access="FIELD">
  <table name="PART_PROJECT"/>
  <range-partitioning name="RangePartitioningByPROJ_ID" partition-value-type="java.lang.Integer" union-unpartitionable-queries="true">
    <partition-column name="PROJ_ID"/>
    <partition connection-pool="default" start-value="0" end-value="1000"/>
    <partition connection-pool="node2" start-value="1000" end-value="2000"/>
    <partition connection-pool="node3" start-value="2000"/>
  </range-partitioning>
  <partitioned>RangePartitioningByPROJ_ID</partitioned>
</entity>


See Also

For more information, see:


@ReadOnly

Use @ReadOnly to specify that a class is read-only.


Annotation Elements

This annotation contains no elements.


Usage

It may be defined on an Entity or MappedSuperclass.

In the case of inheritance, a @ReadOnly annotation can only be defined on the root of the inheritance hierarchy .

You can also use @ReadOnly to bypass EclipseLink's persistence context to save heap space (such as if you need to load a large dataset).


NoteNote:

You should not modify read-only entities. Doing so can corrupt the EclipseLink cache. To modify a read-only entity, it must cloned or serialized.



Examples

Example 2-100 shows how to use this annotation.

Example 2-100 Using @ReadOnly Annotation

@ReadOnly
@Entity
@Table(name = "TMP_READONLY")
public class ReadOnlyEntity {
...
}

Example 2-101 shows how to use the <read-only> element in the eclipselink-orm.xml file.

Example 2-101 Using <read-only> XML

<entity name="XMLReadOnlyClass" class="ReadOnlyClass" access="PROPERTY" read-only="true">


See Also

For more information, see:


@ReadTransformer

Use @ReadTransformer with Transformation mappings to define the transformation of the database column values into attribute values (unless the mapping is write-only).


Annotation Elements

Table 2-65 describes this annotation's elements.

Table 2-65 @ReadTransformer Annotation Elements

Annotation Element Description Default

method

The mapped class must have a method with this name which returns a value to be assigned to the attribute (not assigns the value to the attribute).


transformerClass

User-defined class that implements the org.eclipse.persistence.mappings.transformers.AttributeTransformer interface

The class will be instantiated, its buildAttributeValue will be used to create the value to be assigned to the attribute.

void.class



NoteNote:

You must specify either a method or transformerClass, but not both.



Usage

Also unless it's a read-only mapping, either @WriteTransformer annotation or @WriteTransformers annotation should be specified. Each WriteTransformer defines transformation of the attribute value to a single database column value (column is specified in the WriteTransformer).


Examples

See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation with a Transformation mapping.


See Also

For more information, see:


@ReplicationPartitioning

Use @ReplicationPartitioning to send requests to a set of connection pools. It is for replicating data across a cluster of database machines. Only modification queries are replicated.


Annotation Elements

Table 2-66 describes this annotation's elements.

Table 2-66 @ReplicationPartitioning Annotation Elements

Annotation Element Description Default

name

The name of the partition policy; must be unique for the persistence unit


connectionPools

List of connection pool names to replicate across

All defined pools in the ServerSession



Usage

Partitioning can be enabled on an Entity, relationship, query, or session/persistence unit.

Partition policies are globally named to allow reuse, the partitioning policy must also be set using the @Partitioned annotation to be used.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "Using Partitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@ReturnInsert

Use @ReturnInsert to cause INSERT operations to return values back into the object being written. This allows for table default values, trigger or stored procedures computed values to be set back into the object.


NoteNote:

Returning is only supported with an Oracle Database and requires an INSERT RETURNING clause.

To use returning with other databases, a stored procedure with output parameters is used for the insert query.



Annotation Elements

Table 2-67 describes this annotation's elements.

Table 2-67 @ReturnInsert Annotation Elements

Annotation Element Description Default

returnOnly

(Optional) If specified (true), the mapping field will be excluded from the INSERT clause during SQL generation.

false



Usage

A @ReturnInsert annotation can only be specified on a Basic mapping.


Examples

Example 2-102 shows how to use the @ReturnInsert annotation. If you do not use an argument, EclipseLink accepts the default value, false.

Example 2-102 Using @ReturnInsert Annotation

@ReturnInsert(returnOnly=true)
 public String getFirstName() {
     return firstName;
 }

Example 2-103 shows how to use the <return-insert> element in the eclipselink-orm.xml file.

Example 2-103 Using <return-insert> XML

<basic name="firstName">
    <column name="FIRST_NAME"/>
    <return-insert read-only="true"/>
</basic>


See Also

For more information, see:


@ReturnUpdate

Use @ReturnUpdate to cause UPDATE operations to return values back into the object being written. This allows for table default values, trigger or stored procedures computed values to be set back into the object.


NoteNote:

Returning is only supported with an Oracle Database and requires an INSERT RETURNING clause.

To use returning with other databases, a stored procedure with output parameters is used for the insert query.



Annotation Elements

This annotation contains no elements.


Usage

A @ReturnUpdate annotation can only be specified on a Basic mapping.


Examples

Example 2-104 shows how to use the @ReturnUpdate annotation. The annotation does not accept any arguments.

Example 2-104 Using @ReturnUpdate Annotation

@ReturnUpdate
public String getFirstName() {
    return firstName;
}

Example 2-105 illustrates the same example as before, but uses the <return-update> element in the eclipselink-orm.xml mapping file.

Example 2-105 Using <return-update> XML

<basic name="firstName">
    <column name="F_NAME"/>
    <return-update/>
</basic>


See Also

For more information, see:


@RoundRobinPartitioning

Use @RoundRobinPartitioning to send requests in a "round robin" fashion to the set of connection pools.


Annotation Elements

Table 2-68 describes this annotation's elements.

Table 2-68 @RoundRobinPartitioning Annotation Elements

Annotation Element Description Default

name

(Required) Name of the partition policy. Names must be unique for the persistence unit.


connectionPools

(Optional) List of connection pool names to load balance across

All defined pools in the ServerSession

replicateWrite

(Optional) This allows for a set of database to be written to and kept in sync, and have reads load-balanced across the databases.

false



Usage

Use the @RoundRobinPartitioning annotation for load-balancing read queries across a cluster of database machines. Using @RoundRobinPartitioning requires that the full database be replicated on each machine.

The data should either be read-only, or writes should be replicated on the database.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "@Partitioned" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@SerializedObject

Use an @SerializedObject annotation to set an org.eclipse.persistence.descriptors.SerializedObjectPolicy instance on an Entity object or MappedSuperClass object. If a serialized object policy is specified, a whole entity object is written with its privately-owned (and nested, privately-owned) entities and element collections into an additional field in the database.


Annotation Elements

Table 2-69 describes this annotation's elements.

Table 2-69 @SerializedObject Attribute Elements

Annotation Element Description Default

column

(Optional) The column that holds the serialized object

BLOB column named SOP in the entity's main table.

value

(Required) The Class that implements the
SerializedObjectPolicy
interface




Usage

Use an @SerializedObject annotation to read data from the database faster. The drawback to this usage is that writing to the database is slower. Use a serialized object policy for read-only and read-mostly applications for entities and element collections.

If the serialized object column contains null or an obsolete version of the object, then a query using a serialized object policy would either throw an exception or, if all other fields have been read as well, build the object using these fields (exactly as in the case where a serialized object policy is not used).


NoteNote:

Currently, no default implementation of the SerializedObjectPolicy interface is available. You must provide this class.



Examples

Example 2-106 demonstrates how to use the @SerializedObject annotation to specify a serialized object policy and how to override the default column name.

Example 2-106 Specifying a Serialized Object Policy

@Entity
@SerializedObject(MySerializedPolicy.class);
public class Employee {...

@Entity
@SerializedObject(value = MySerializedObjectPolicy.class, column = @Column(name = "SERIALIZED"));
public class Address (...

If an @SerializedObject annotation is set on an entity object, then read queries (in addition to find and refresh) that return the object use the serialized object policy by default.

Example 2-107 demonstrates how to prevent using the serialized object policy in a query.

Example 2-107 Preventing the Use of a Serialized Object Policy in a Query

Query query = em.createQuery("SELECT e FROM Employee e")
.setHint(QueryHints.SERIALIZED_OBJECT, "false");

Example 2-108 demonstrates how to use a serialized object policy property to prevent searching for a serialized object. .

Example 2-108 Preventing Search Using a Serialized Object Policy Property

Map hints = new HashMap();
hints.put("eclipselink.serialized-object", "false");
Address address = em.find(Address.class, id, hints);


See Also

For more information:


@StoredProcedureParameter

Use @StoredProcedureParameter within a NamedStoredProcedureQuery annotation.


Annotation Elements

Table 2-70 describes this annotation's elements.

Table 2-70 @StoredProcedureParameter Annotation Elements

Annotation Element Description Default

queryParameter

(Required) The query parameter name


direction

(Optional) The direction of the stored procedure parameter:

  • IN – Input parameter

  • IN_OUT – Input and output parameters

  • OUT – Output parameter

  • OUT_CURSOR – Output cursor

IN

jdbcType

(Optional) JDBC type code. This depends on the type returned from the procedure.

-1

jdbcTypeName

(Optional) JDBC type name. This may be required for ARRAY or STRUCT types.


name

(Optional) Stored procedure parameter name


optional

(Optional) Specify if the parameter is required, or optional and defaulted by the procedure.

false

type

(Optional) Type of Java class desired back from the procedure. This depends on the type returned from the procedure.

void.class



Examples

See "@NamedStoredProcedureQuery" for an example using the @StoredProcedureParameter annotation.


See Also

For more information:


@Struct

Use @Struct to define a class to map to a database Struct type. The class should normally be an Embeddable, but could also be an Entity if stored in a object table.


Annotation Elements

Table 2-71 describes this annotation's elements.

Table 2-71 @Struct Annotation Elements

Annotation Element Description Default

name

(Required) The database name of the database structure type


fields

(Optional) Defines the order of the fields contained in the database structure type.




Usage

Struct types are extended object-relational data-types supported by some databases. Struct types are user define types in the database such as OBJECT types on Oracle. Structs normally contain Arrays (VARRAY) or other Struct types, and can be stored in a column or a table.

You can also use Struct types to call PL/SQL stored procedures that use RECORD types in an Oracle Database.


Examples

Example 2-109 shows using the @Struct annotation to define a Java class to map to an OBJECT type.

Example 2-109 Using @Struct Annotation

@Embeddable
@Struct(name="EMP_TYPE", fields={"F_NAME", "L_NAME", "SALARY"})
public class Employee {
 @Column(name="F_NAME")
 private String firstName;
 @Column(name="L_NAME")
 private String lastName;
 @Column(name="SALARY")
 private BigDecimal salary;
 ...
}

Example 2-110 shows how to use the <struct> element in the eclipselink-orm.xml file.

Example 2-110 Using <struct> XML

<embeddable class="Address" access="FIELD">
  <struct name="PLSQL_P_PLSQL_ADDRESS_REC">
    <field>ADDRESS_ID</field>
    <field>STREET_NUM</field>
    <field>STREET</field>
    <field>CITY</field>
    <field>STATE</field>
  </struct>
  <attributes>
    <basic name="id">
      <column name="ADDRESS_ID"/>
    </basic>
    <basic name="number">
      <column name="STREET_NUM"/>
    </basic>
  </attributes>
</embeddable>


See Also

For more information, see:


@StructConverter

Use @StructConverter to enable custom processing of java.sql.Struct types to process complex database types, such as spatial datatypes.

EclipseLink includes the JGeometryConverter class to convert the Oracle JGeometry spatial datatype.


NoteNote:

Unlike other converters, @StructConverter has its own interface.



Annotation Elements

Table 2-72 describes this annotation's elements.

Table 2-72 @StructConverter Annotation Elements

Annotation Element Description Default

name

The String name for your converter. Ensure that this name is unique across the persistence unit.

none

converter

The converter class as a String. This class must implement the org.eclipse.persistence.platform.database.converters.StructConverter interface.

none



Usage

You can use the existing @Convert annotation with its value attribute set to the StructConverter name – in this case, the appropriate settings are applied to the mapping. This setting is required on all mappings that use a type for which a StructConverter has been defined. Failing to configure the mapping with the @Convert will cause an error.

EclipseLink also includes additional converters, such as @ObjectTypeConverter and @TypeConverter.


Examples

Example 2-111 shows how to define the @StructConverter annotation.

Example 2-111 Using @StructConverter Annotation

@StructConverter(
     name="JGeometryConverter"
     converter=JGeometryConverter.class.getName())

You can specify the @StructConverter annotation anywhere in an Entity with the scope being the whole session. An exception is thrown if you add more than one StructConverter annotation that affects the same Java type. An @StructConverter annotation exists in the same namespaces as @Converter. A validation exception is thrown if you add an @Converter and an @StructConverter of the same name.


See Also

For more information, see:


@StructConverters

Use @StructConverters to define multiple @StructConverter annotations.


Annotation Elements

Table 2-73 describes this annotation's elements.

Table 2-73 @StructConverters Annotation Elements

Annotation Element Description Default

StructConverter[]

(Required) An array of struct converter




Examples

Example 2-112 shows how to use the @StructConverters annotation to define multiple @StructConverter elements.

Example 2-112 Using @StructConverters Annotation

@StructConverters{{
  @StructConverter(name="StructConverter1", converter="foo.StructConverter1"),
  @StructConverter(name="StructConverter2", converter="foo.StructConverter2")
  })

Example 2-113 shows how to use the <struct-converters> element in the eclipselink-orm.xml file.

Example 2-113 Using <struct-converters> XML

<struct-converters>
  <struct-converter name="StructConverter1" converter="foo.StructConverter1"/>
  <struct-converter name="StructConverter2" converter="foo.StructConverter2"/>
</struct-converters>


See Also

For more information, see:


@Structure

Use @Structure on a field/method to define a StructureMapping to an embedded Struct type. The target Embeddable must be mapped using the Struct annotation.


Annotation Elements

This annotation contains no elements.


Usage

Struct types are extended object-relational data-types supported by some databases. Struct types are user define types in the database such as OBJECT types on Oracle. Structs can normally contains Arrays (VARRAY) or other Struct types, and can be stored in a column or a table.


Examples

Example 2-114 shows how to use the @Structure annotation. See Example 2-109 to an example of using @Struct to map the target.

Example 2-114 Using @Structure Annotation

@Structure
protected Address address;
 

You can also define structure mappings in the eclipselink-orm.xml file by using the <structure> element.

Example 2-115 Using <structure> XML

<structure name="address"/>
 


See Also

For more information, see:


@TenantDiscriminatorColumn

The @TenantDiscriminator annotation is used with the @Multitenant annotation and the SINGLE-TABLE mulitenant type to limit what a persistence context can access in single-table mulitenancy.


Annotation Elements

Table 2-74 describes this annotation's elements.

Table 2-74 @TenantDiscriminatorColumn Properties

Annotation Element Description Default

java.lang.String columnDefinition

(Optional) The SQL fragment that is used when generating the DDL for the discriminator column

The provider-generated SQL to create a column of the specified discriminator type.

java.lang.String contextProperty

(Optional) The name of the context property to apply to the tenant discriminator column

eclipselink.tenant-id

DiscriminatorType discriminatorType

(Optional) The type of object/column to use as a class discriminator

javax.persistence.DiscriminatorType.STRING

int length

(Optional) The column length for String-based discriminator types

The column length for String-based discriminator types. Ignored for other discriminator types.

java.lang.String name

(Optional) The name of column to be used for the tenant discriminator

TENANT_ID

boolean primaryKey

Specifies that the tenant discriminator column is part of the primary key of the tables.

false

java.lang.String table

(Optional) The name of the table that contains the column

The name of the table that contains the column. If absent the column is assumed to be in the primary table. This attribute must be specified if the column is on a secondary table.



Usage

To configure single-table multi-tenancy, you must specify both of the following:

Using Discriminator Columns

The following characteristics apply to discriminator columns:

Using Single-Table Multi-Tenancy in an Inheritance Hierarchy

Inheritance strategies are configured by specifying the inheritance type (see @javax.persistence.Inheritance). Single-table multi-tenancy can be used in an inheritance hierarchy, as follows:


Examples

Table 2-74 shows a number of uses of tenant discriminator columns.

Example 2-116 Using @TenantDiscriminatorColumn Annotation

/** Single tenant discriminator column **/
 
@Entity
@Table(name = "CUSTOMER")
@Multitenant
@TenantDiscriminatorColumn(name = "TENANT", contextProperty = "multi-tenant.id")
public Customer() {
  ...
}
 
 
/** Multiple tenant discriminator columns using multiple tables **/
 
@Entity
@Table(name = "EMPLOYEE")
@SecondaryTable(name = "RESPONSIBILITIES")
@Multitenant(SINGLE_TABLE)
@TenantDiscriminatorColumns({
    @TenantDiscriminatorColumn(name = "TENANT_ID", contextProperty = "employee-tenant.id", length = 20)
    @TenantDiscriminatorColumn(name = "TENANT_CODE", contextProperty = "employee-tenant.code", discriminatorType = STRING, table = "RESPONSIBILITIES")
  }
)
public Employee() {
  ...
}
 
 
/** Tenant discriminator column mapped as part of the primary key on the database **/
 
@Entity
@Table(name = "ADDRESS")
@Multitenant
@TenantDiscriminatorColumn(name = "TENANT", contextProperty = "tenant.id", primaryKey = true)
public Address() {
  ...
}
 
 
/** Mapped tenant discriminator column **/
 
@Entity
@Table(name = "Player")
@Multitenant
@TenantDiscriminatorColumn(name = "AGE", contextProperty = "tenant.age")
public Player() {
  ...
 
  @Basic
  @Column(name="AGE", insertable="false", updatable="false")
  public int age;
}

Example 2-117 shows the same mappings, using the <tenant-disciminator-column> XML element in the eclipselink-orm.xml file.

Example 2-117 Using <tenant-discriminator-column> XML

<!-- Single tenant discriminator column -->
 
<entity class="model.Customer">
  <multitenant>
    <tenant-discriminator-column name="TENANT context-property="multi-tenant.id""/>
  </multitenant>
  <table name="CUSTOMER"/>
  ...
</entity>
 
<!-- Multiple tenant discriminator columns using multiple tables -->
 
<entity class="model.Employee">
  <multitenant type="SINGLE_TABLE">
    <tenant-discriminator-column name="TENANT_ID" context-property="employee-tenant.id" length="20"/>
    <tenant-discriminator-column name="TENANT_CODE" context-property="employee-tenant.id" discriminator-type="STRING" table="RESPONSIBILITIES"/>
  </multitenant>
  <table name="EMPLOYEE"/>
  <secondary-table name="RESPONSIBILITIES"/>
  ...
</entity>
 
<!-- Tenant discriminator column mapped as part of the primary key on the database -->
 
<entity class="model.Address">
  <multitenant>
    <tenant-discriminator-column name="TENANT" context-property="multi-tenant.id" primary-key="true"/>
  </multitenant>
  <table name="ADDRESS"/>
  ...
</entity>
 
<!-- Mapped tenant discriminator column -->
 
<entity class="model.Player">
  <multi-tenant>
    <tenant-discriminator-column name="AGE" context-property="tenant.age"/>
  </multi-tenant>
  <table name="PLAYER"/>
  ...
  <attributes>
    <basic name="age" insertable="false" updatable="false">
      <column name="AGE"/>
    </basic>
    ...
  </attributes>
  ...
</entity>


See Also


@TenantDiscriminatorColumns

Specify multiple discriminator columns for single-table multitenancy by using the @TenantDiscriminatorColumns annotation to contain multiple @TenantDiscriminatorColumn annotations.


Annotation Elements

Table 2-75 describes this annotation's elements.

Table 2-75 @TenantDiscriminatorColumns Annotation Elements

Annotation Element Description Default

TenantDiscriminatorColumn value

(Optional) One or more TenantDiscriminatorColumn annotations

none



Usage

You must use the @TenantDiscriminatorColumns annotation to contain multiple @TenantDiscriminatorColumn annotations. The @TenantDiscriminatorColumns annotation cannot be used alone, and multiple the @TenantDiscriminatorColumn annotations cannot be used alone, without @TenantDiscriminatorColumns.


Examples

@Entity 
@Table(name = "EMPLOYEE") 
@Multitenant(SINGLE_TABLE) 
@TenantDiscriminatorColumns({ 
    @TenantDiscriminatorColumn(name = "TENANT_ID", contextProperty = ”tenant-id)
    @TenantDiscriminatorColumn(name = "TENANT_CODE", contextProperty = ”tenant-code)})

See "@TenantDiscriminatorColumn" for more examples of @TenantDiscriminatorColumns.


See Also


@TenantTableDiscriminator

Table-per-tenant multitenancy allows multiple tenants of an application to isolate their data in one or more tenant-specific tables. The tenant table discriminator specifies how to discriminate the tenant's tables from the other tenants' tables in a table-per-tenant multitenancy strategy.


Annotation Elements

Table 2-76 describes this annotation's elements.

Table 2-76 @TenantTableDiscriminator Annotation Elements

Annotation Element Description Default

java.lang.String ContextProperty

(Optional) Name of the context property to apply to as tenant table discriminator

eclipselink.tenant-id

TenantTableDiscriminator type

(Optional) Type of tenant table discriminator to use with the tables of the persistence unit:

  • SCHEMA

  • SUFFIX

  • PREFIX

SUFFIX



Usage

In table-per-tenant multitenancy, tenants' tables can be in the same schema, using a prefix or suffix naming pattern to distinguish them; or they can be in separate schemas. The tenant table discriminator identifies whether to use the prefix or suffix naming pattern or to use a separate schema to identify and isolate the tenant's tables from other tenants' tables. The types are:

Tenant table discriminator can be specified at the entity or mapped superclass level and must always be used with Multitenant(TABLE_PER_TENANT). It is not sufficient to specify only a tenant table discriminator.

For more information about using @TenantTableDiscriminator and table-per-tenant multitenancy, see "@Multitenant".


Examples

The following example shows a SCHEMA-type table discriminator.

Example 2-118 Using @TenantTableDiscriminator Annotation

@Entity
@Table(name=”EMP”)
@Multitenant(TABLE_PER_TENANT)
@TenantTableDiscriminator(type=SCHEMA, contextProperty="eclipselink.tenant-id")
public class Employee {
    ...
}
 

Example 2-119 Using <tenant-table-discriminator> XML

<entity class="Employee">
  <multitenant type="TABLE_PER_TENANT">
    <tenant-table-discriminator type="SCHEMA" context-property="eclipselink.tenant-id"/>
  </multitenant>
  <table name="EMP">
  ...
</entity>


See Also


@TimeOfDay

Use @TimeOfDay to specify a specific time of day using a Calendar instance which is to be used within an @Cache annotation.


Annotation Elements

Table 2-77 describes this annotation's elements.

Table 2-77 @TimeOfDay Annotation Elements

Annotation Element Description Default

hour

(Optional) Hour of the day

0

millisecond

(Optional) Millisecond of the day

0

minute

(Optional) Minute of the day

0

second

(Optional) Second of the day

0

specified

For internal use – do not modify

true



Examples

See "@Cache" for examples of using @TimeOfDay.


See Also

For more information, see:


@Transformation

Use @Transformation with a Transformation mapping to define the transformation of database columns into attribute values (unless the Transformation mapping is write-only, in which case it should have a @ReadTransformer annotation).


Annotation Elements

Table 2-78 describes this annotation's elements.

Table 2-78 @Transformation Annotation Elements

Annotation Element Description Default

fetch

(Optional) Defines whether the value of the field or property should be lazily loaded or must be eagerly fetched.

  • The EAGER strategy is a requirement on the persistence provider runtime that the value must be eagerly fetched.

  • The LAZY strategy is a hint to the persistence provider runtime.

EAGER

optional

(Optional) A hint as to whether the value of the field or property may be null. It is disregarded for primitive types, which are considered non-optional.

true



Usage

Unless it's a read-only mapping, either WriteTransformer annotation or WriteTransformers annotation should be specified. Each WriteTransformer defines transformation of the attribute value to a single database column value (column is specified in the WriteTransformer).


Examples

Example 2-120 shows how to use the @Transformation annotation.

Example 2-120 Using @Transformation Annotation

@Transformation(fetch=FecthType.LAZY, optional="true")
@ReadTransformer(class=package.MyNormalHoursTransformer.class)
@WriteTranformers({
   @WriteTranformer(column=@Column(name="START_TIME"), 
      method="getStartDate"),
   @WriteTranformer(column=@Column(name="END_TIME"), 
      class=package.MyTimeTransformer.class)
})
@Mutable
@ReturnUpdate
@Access(AccessType.PROPERTY)
@AccessMethods(get="getNormalHours", set="setNormalHours")
@Properties({
   @Property(name="x", value="y")
})

Example 2-121 shows the same mapping, using the <transformation> XML element in the eclipselink-orm.xml file.

Example 2-121 Using <transformation> XML

<transformation name="normalHours" fetch="LAZY" optional="true">
     <read-transformer method="buildNormalHours"/>
     <write-transformer method="getStartTime">
             <column name="START_TIME"/>
     </write-transformer>
     <write-transformer class="package.MyTimeTransformer">
             <column name="END_TIME"/>
     </write-transformer>
     <mutable/>
     <return-update/>
     <access type="PROPERTY"/>
     <access-methods get="getNormalHours" set="setNormalHours"/>
     <properties>
        <property name="x" value="y"/>
     </properties>
</transformation>


See Also

For more information, see:


@TypeConverter

Use @TypeConverter to modify data values during the reading and writing of a mapped attribute.


Annotation Elements

Table 2-79 describes this annotation's elements.

Table 2-79 @TypeConverter Annotation Elements

Annotation Element Description Default

name

(Required) The String name for your converter. This name must be unique across the persistence unit.

none

dataType

(Optional) The type stored in the database

void.classFoot 

objectType

(Optional) The type stored on the entity

void.classFootref 1


Footnote The default is inferred from the type of the persistence field or property.


Usage

Each TypeConverter must be uniquely named and can be defined at the class, field and property level and can be specified within an Entity, MappedSuperclass and Embeddable class. A TypeConverter is always specified by using an @Convert annotation

You can place a @TypeConverter on a Basic, BasicMap or BasicCollection mapping.

EclipseLink also includes @ObjectTypeConverter and @StructConverter converters.


Examples

Example 2-122 shows how to use the @TypeConverter annotation to convert the Double value stored in the database to a Float value stored in the entity.

Example 2-122 Using the @TypeConverter Annotation

@Entity
public class Employee implements Serializable{

...

  @TypeConverter (
    name="doubleToFloat",
    dataType=Double.class,
    objectType=Float.class,
  )
  @Convert("doubleToFloat")
  public Number getGradePointAverage() {
    return gradePointAverage;
  }

...
}


See Also

For more information, see:


@TypeConverters

Use @TypeConverters to define multiple TypeConverter elements.


Annotation Elements

Table 2-80 describes this annotation's elements.

Table 2-80 @TypeConverters Annotation Elements

Annotation Element Description Default

TypeConverter[]

(Required) An array of type converter




Examples

Example 2-123 shows how to use this annotation.

Example 2-123 Using @TypeConverters Annotation

@Entity
@TypeConverters({
    @TypeConverter(name="BigIntegerToString",dataType=String.class,objectType=BigInteger.class)
    })
public class Parameters implements Serializable {
    private static final long serialVersionUID = -1979843739878183696L;
    @Column(name="maxValue", nullable=false, length=512)
    @Convert("BigIntegerToString")
    private BigInteger maxValue;
...
}

Example 2-123 shows how to use the <type-converters> element in the eclipselink-orm.xml file.

Example 2-124 Using <type-converters> XML

<type-converters>
    <type-converter name="Long2String" data-type="String" object-type="Long"/>
    <type-converter name="String2String" data-type="String" object-type="String"/>
</type-converters>
<entity class="Employee">
...
</entity>


See Also

For more information, see:


@UnionPartitioning

Use @UnionPartitioning to send queries to all connection pools and then union the results. This can be used for queries or relationships that span partitions when partitioning is used, such as on a ManyToMany cross partition relationship.


Annotation Elements

Table 2-81 describes this annotation's elements.

Table 2-81 @UnionPartitioning Annotation Elements

Annotation Element Description Default

name

Name of the partition policy. Names must be unique for the persistence unit.


connectionPools

List of connection pool names to load balance across

Defaults to all defined pools in the ServerSession

replicateWrite

Defines if write queries should be replicated.

Writes are normally not replicated when unioning, but can be for ManyToMany relationships, when the join table needs to be replicated.

false



Usage

Partitioning can be enabled on an Entity, relationship, query, or session/persistence unit. Partition policies are globally named to allow reuse, the partitioning policy must also be set using the @Partitioned annotation to be used.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "Using Partitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@UuidGenerator

Use @UuidGenerator to defines a primary key generator that may be referenced by name when a generator element is specified for the @GeneratedValue annotation. A UUID (universally unique identifier) generator may be specified on the entity class or on the primary key field or property.

The generator name is global to the persistence unit (that is, across all generator types).


Annotation Elements

Table 2-82 describes this annotation's elements.

Table 2-82 @UuidGenerator Annotation Elements

Annotation Element Description Default

name

Name of the UUID generator, which must be unique for the persistence unit




Examples

Example 2-125 shows how to use this annotation.

Example 2-125 Using @UuidGenerator Annotation

@Entity
@UuidGenerator(name="EMP_ID_GEN")
public class Employee {
    @Id
    @GeneratedValue(generator="EMP_ID_GEN")
    private String id;
}

You can also specify the SessionCustomizer and configure the named sequence in your eclipselink-orm.xml file, as shown in Example 2-126.

Example 2-126 Using <generated-value> XML

<id name="id">
    <column name="PROJ_ID" />
    <generated-value generator="system-uuid"/>
</id>

You can also specify the named sequence at the persistence unit level (in the persistence.xml file) as shown in Example 2-127.

Example 2-127 Specifying Generator in persistence.xml

<property name="eclipselink.session.customizer" value="eclipselink.example.UUIDSequence"/>


See Also

For more information, see:


@UnionPartitioning

Use @UnionPartitioning to send queries to all connection pools and then union the results. This can be used for queries or relationships that span partitions when partitioning is used, such as on a ManyToMany cross partition relationship.


Annotation Elements

Table 2-81 describes this annotation's elements.

Table 2-83 @UnionPartitioning Annotation Elements

Annotation Element Description Default

name

Name of the partition policy. Names must be unique for the persistence unit.


connectionPools

List of connection pool names to load balance across

Defaults to all defined pools in the ServerSession

replicateWrite

Defines if write queries should be replicated.

Writes are normally not replicated when unioning, but can be for ManyToMany relationships, when the join table needs to be replicated.

false



Usage

Partitioning can be enabled on an Entity, relationship, query, or session/persistence unit. Partition policies are globally named to allow reuse, the partitioning policy must also be set using the @Partitioned annotation to be used.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "Using Partitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@ValuePartition

Use @ValuePartition to represent a specific value partition that will be routed to a specific connection pool.


Annotation Elements

Table 2-84 describes this annotation's elements.

Table 2-84 @ValuePartition Annotation Elements

Annotation Element Description Default

connectionPool

The connection pool to which to route queries to for the value


value

The String representation of the value




Examples

Example 2-128 shows how to use the @ValuePartition and @ValuePartitioning annotations.

Example 2-128 Using @ValuePartition Annotation

@Entity
@Table(name = "PART_EMPLOYEE")
@IdClass(EmployeePK.class)
@ValuePartitioning(
  name="ValuePartitioningByLOCATION",
  partitionColumn=@Column(name="LOCATION"),
  unionUnpartitionableQueries=true,
  defaultConnectionPool="default",
  partitions={
    @ValuePartition(connectionPool="node2", value="Ottawa"),
    @ValuePartition(connectionPool="node3", value="Toronto")
  })
@Partitioned("ValuePartitioningByLOCATION")
public class Employee implements Serializable, Cloneable {
...
}

Example 2-129 shows how to use the <partition> element in the eclipselink-orm.xml file.

Example 2-129 Using <partition> XML

<entity name="Employee" class="Employee" access="FIELD">
  <table name="PART_EMPLOYEE"/>
  <id-class class="EmployeePK"/>
  <value-partitioning name="ValuePartitioningByLOCATION" union-unpartitionable-queries="true" default-connection-pool="default">
    <partition-column name="LOCATION"/>
    <partition connection-pool="node2" value="Ottawa"/>
    <partition connection-pool="node3" value="Toronto"/>
  </value-partitioning>
<partitioned>ValuePartitioningByLOCATION</partitioned>


See Also

For more information, see:


@ValuePartitioning

Use @ValuePartitioning to partition access to a database cluster by a field value from the object (such as the object's location or tenant). Each value is assigned a specific server. All write or read request for object's with that value are sent to the server. If a query does not include the field as a parameter, then it can either be sent to all server's and unioned, or left to the session's default behavior.


Annotation Elements

Table 2-85 describes this annotation's elements.

Table 2-85 @ValuePartitioning Annotation Elements

Annotation Element Description Default

name

(Required) Name of the partition policy. Names must be unique for the persistence unit.


partitionColumn

(Required) The database column or query parameter to partition queries by

This is the table column name, not the class attribute name. The column value must be included in the query and should normally be part of the object's ID. This can also be the name of a query parameter.

If a query does not contain the field the query will not be partitioned.


partitions

(Required) Store the value partitions. Each partition maps a value to a connectionPool.


defaultConnectionPool

(Optional) The default connection pool is used for any unmapped values


partitionValueType

(Optional) The type of the start and end values

String

unionUnpartitionableQueries

(Optional) Defines if queries that do not contain the partition field should be sent to every database and have the result unioned.

false



Usage

Partitioning can be enabled on an Entity, relationship, query, or session/persistence unit. Partition policies are globally named to allow reuse, the partitioning policy must also be set using the @Partitioned annotation to be used.

The persistence unit properties support adding named connection pools in addition to the existing configuration for read/write/sequence. A named connection pool must be defined for each node in the database cluster.

If a transaction modifies data from multiple partitions, you should use JTA ensure proper two-phase commit of the data. You can also configure an exclusive connection in the EntityManager to ensure that only a single node is used for a single transaction.


Examples

See "Using Partitioning" for an example of partitioning with EclipseLink.


See Also

For more information, see:


@VariableOneToOne

Use @VariableOneToOne to represent a pointer references between a java object and an implementer of an interface. This mapping is usually represented by a single pointer (stored in an instance variable) between the source and target objects. In the relational database tables, these mappings are normally implemented using a foreign key and a type code.


Annotation Elements

Table 2-86 describes this annotation's elements.

Table 2-86 @VariableOneToOne Annotation Elements

Annotation Element Description Default

CascadeType

(Optional) Array of operations that must be cascaded to the target of the association


DiscriminatorClasses

(Optional) Array of discriminator types that can be used with this mapping

If none are specified, EclipseLink adds entities within the persistence unit that implement the target interface.

If DiscriminatorColumn is STRING, EclipseLink uses Entity.name().

If DiscriminatorColumn is CHAR, EclipseLink uses the first letter of the entity class.

If DiscriminatorColumn is INTEGER, EclipseLink uses the next integer after the highest integer explicitly stated.

DiscriminatorColumn

(Optional) The discriminator column that contains the type identifiers

DTYPE

FetchType

(Optional) Specify how the value of the field or property should be loaded:

  • Eager: Requires that the persistence provider runtime must eagerly fetch the value

  • Lazy: Hints that the persistence provider should lazily load the value

Eager

Optional

(Optional) Specify if the association is optional.


OrphanRemoval

(Optional) Specify if interface class that is the target of this mapping.


TargetInterface

(Optional) The interface class that is the target of this mapping

If none is specified, EclipseLink will infer the interface class based on the type of object being referenced.



Usage

You can specify @VariableOneToOne on an Entity, MappedSuperclass, or Embeddable class.


Examples

Example 2-130 shows how to use the @VariableOneToOne annotation.

Example 2-130 Using @VariableOneToOne Annotation

@VariableOneToOne(
    cascade={ALL},
    fetch=LAZY,
    discriminatorColumn=@DiscriminatorColumn(name="CONTACT_TYPE"),
    discriminatorClasses={
        @DiscriminatorClass(discriminator="E", value="Email.class"), 
        @DiscriminatorClass(discriminator="P", value="Phone.class")
    }
}
@JoinColumn(name="CONTACT_ID", referencedColumnName="C_ID")
@PrivateOwned
@JoinFetch(INNER)
public Contact getContact() {
    return contact;
}

Example 2-131 shows the same mapping using the <variable-one-to-one> XML element in the eclipselink-orm.xml file.

Example 2-131 Using <variable-one-to-one> XML

<variable-one-to-one name="contact" fetch="LAZY">
    <cascade>
        <cascade-all/>
    </cascade>
    <discriminator-column name="CONTACT_TYPE"/>
    <discriminator-class discriminator="E" value="Email.class"/>
    <discriminator-class discriminator="P" value="Phone.class"/>
    <join-column name="CONTACT_ID" referenced-column-name="C_ID"/>
    <private-owned/>
    <join-fetch>INNER</join-fetch>
</variable-one-to-one>


See Also

For more information, see:


@VirtualAccessMethods

Use @VirtualAccessMethods to specify that a specific class contains virtual methods.


Annotation Elements

Table 2-87 describes this annotation's elements.

Table 2-87 @VirtualAccessMethods Annotation Elements

Annotation Element Description Default

get

(Optional) Name of the getter method to use for the virtual property. This method must take a single java.lang.String parameter and return a java.lang.Object.

If get is specified, you must also specify set.

get

set

(Optional) Name of the setter method to use for the virtual property. This method must take a java.lang.String parameter and a java.lang.Object parameter.

If set is specified, you must also specify get.

set



Usage

Use the @VirtualAccessMethods annotation to define access methods for mappings with in which accessType=VIRTUAL.


Examples

Table 2-87 shows an entity using property access.

Example 2-132 Using @VirtualAccessMethods Annotation

@Entity
  @VirtualAccessMethods
  public class Customer{
 
    @Id
    private int id;
...
 
    @Transient
    private Map<String, Object> extensions;
 
    public <T> T get(String name) {
        return (T) extensions.get(name);
    }
 
    public Object set(String name, Object value) {
        return extensions.put(name, value);
    }

In addition to using the @VirtualAccessMethods annotation, you can use the <access> and <access-method> elements in your eclipselink-orm.xml file, as shown in Example 2-133.

Example 2-133 Using <access> and <access-methods> XML

<access>VIRTUAL</access><access-methods get-method="get" set-method="set"/>@Entity


See Also

For more information, see:


@WriteTransformer

Use @WriteTransformer on a TranformationMapping to transform a single attribute value to a single database column value. Use the @WriteTransformers annotation to wrap multiple transformations.


Annotation Elements

Table 2-88 describes this annotation's elements.

Table 2-88 @WriteTransformer Annotation Elements

Annotation Element Description Default

column

(Optional) The column into which the value should be written

If a single WriteTransfomer annotates an attribute, the attribute's name will be used as the column name.

@javax.persistence.Column

method

(Optional) The String method name that the mapped class must have. This method returns the value to be written into the database column.

Note: To support DDL generation and returning policy, the method should be defined to return a particular type, not just an Object. For example:public Time getStartTime()

The method may require @Transient to avoid being mapped as a Basic by default.


transformerClass

(Optional) User-defined class that implements the FieldTransformer interface. This will instantiate the class and use its buildFieldValue method to create the value to be written into the database column.

Note: To support DDL generation and returningpolicy, the method buildFieldValue in the class should be defined to return the relevant Java type, not just Object as defined in the interface. For example:public Time buildFieldValue(Object instance, String fieldName, Session session).

void.class



NoteNote:

You must specify either transformerClass or method , but not both.



Usage

You cannot define a @WriteTransformer for a read-only mapping.

Unless the TransformationMapping is write-only, it should include a ReadTransformer that defines the transformation of the database column values into attribute values.

Configuring Field Transformer Associations

Using a FieldTransformer is non-intrusive; your domain object does not need to implement an EclipseLink interface or provide a special transformation method.

You can configure a method-based field transformer using AbstractTransformationMapping method addFieldTransformation, passing in the name of the database field and the name of the domain object method to use.

You can configure a class-based field transformer using AbstractTransformationMapping method addFieldTransformer, passing in the name of the database field and an instance of org.eclipse.persistence.mappings.Transfomers.FieldTransformer.

A convenient way to create a FieldTransformer is to extend FieldTransformerAdapter.


Examples

See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation with a Transformation mapping.


See Also

For more information, see:


@WriteTransformers

Use @WriteTransformer on a TranformationMapping to transform a single attribute value to a single database column value. Use the @WriteTransformers annotation to wrap multiple transformations.


Annotation Elements

Table 2-89 describes this annotation's elements.

Table 2-89 @WriteTransformers Annotation Elements

Annotation Element Description Default

WriteTransformer

An array of WriteTransformer




Usage

You cannot use @WriteTransformers for a read-only mapping.


Examples

See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation with a Transformation mapping.


See Also

For more information, see: