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:
The following lists the EclipseLink annotation extensions, categorized by function:
EclipseLink includes the following annotation extensions for mappings:
EclipseLink includes the following annotation extensions for entities:
EclipseLink includes the following annotation extensions for converting data:
EclipseLink includes the following annotation extensions for caching:
EclipseLink includes the following annotation extensions for customization and optimization.
EclipseLink includes the following annotation extensions for copy policies:
EclipseLink includes the following annotation extensions for returning policies:
EclipseLink includes the following annotation extensions for stored procedures and stored functions:
EclipseLink includes the following annotation extensions for using partitions:
EclipseLink includes the following annotation extensions for non-relational datasources:
The following lists the EclipseLink annotation extensions:
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.
Table 2-1 describes this annotation's elements.
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.
Note:
Additional criteria are not supported with native SQL queries.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 include:
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.
Note:
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);
The following example filters data that is marked as deleted (but which still exists in the table) from a query:
@AdditionalCriteria("this.isDeleted = false")
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")
Note:
EclipseLink also provides specific history support, viaHistoryPolicy
. See "History Policy in Understanding EclipseLink for more information.The following example filters on a specific date:
@AdditionalCriteria("this.startDate <= :viewDate and this.endDate >= :viewDate")
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.
Use @Array
to define object-relational data types supported by specific databases, such as Oracle VARRAY
types or PostgreSQL JDBC Array
types.
Table 2-2 describes this annotation's elements.
Table 2-2 @Array Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the database array structure type |
|
|
(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. |
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
.
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.
For more information, see the following:
Solutions Guide for EclispeLink
Use @BatchFetch
to read objects related to a relationship mapping (such as @OneToOne
, @OneToMany
, @ManyToMany
, and @ElementCollection
) to be read in a single query.
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 |
(Optional) The type of batch fetch to use:
|
|
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.
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>
For more information, see:
Solutions Guide for EclispeLink
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.
Table 2-4 describes this annotation's elements.
Table 2-4 @Cache Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Set this attribute to the type (
You can override this attribute with these persistence unit properties:
|
|
|
(Optional) Set this attribute to an int value to define the size of cache to use (number of objects). |
|
|
(Optional) The caching level of the Entity:
|
|
|
(Optional) The |
no expiry |
|
(Optional) Specific time of day ( |
no expiry |
|
(Optional) Set to a boolean value of true to force all queries that go to the database to always refresh the cache |
|
|
(Optional) Set to a boolean value of Note:
|
|
|
(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. |
|
|
(Optional) Set this attribute to the cache coordination mode (
You must also configure cache coordination in your persistence unit properties. See "Caching". |
|
|
(Optional) The database change notification mode:
|
|
Use the @Cache
annotation instead of the JPA @Cachable
annotation to provide additional caching configuration.
You can define the @Cache
annotation on the following:
@Entity
@MappedSuperclass
the root of the inheritance hierarchy (if applicable)
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.
The EclipseLink cache is an in-memory repository that stores recently read or written objects based on class and primary key values. EclipseLink uses the cache to do the following:
Improve performance by holding recently read or written objects and accessing them in-memory to minimize database access.
Manage locking and isolation level.
Manage object identity.
For more information about the EclipseLink cache and its default behavior, see:
"Understanding Caching" in the Understanding EclipseLink
"Object Caching" in Solutions Guide for EclispeLink
EclipseLink defines the following entity caching annotations:
@Cache
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".
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>
For more information, see:
"Understanding Caching" in the Understanding EclipseLink
"Object Caching" in Solutions Guide for EclispeLink
Use @CacheIndex
to define a cached index. Cache indexes are used only when caching is enabled.
Table 2-5 describes this annotation's elements.
Table 2-5 @CacheIndex Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The set of columns on which to define the index. Not required when annotated on a field/method. |
|
|
(Optional) Specify if the indexed field is updateable. If |
true |
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.
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.
Use @CacheIndexes
to define a set of @CacheIndex
on an entity.
Table 2-6 describes this annotation's elements.
Table 2-6 @CacheIndexes Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
An array of cache indexes |
See "@CacheIndex" for examples of using the @CacheIndexes
annotation.
For more information, see:
"About Cache Indexes" in Understanding EclipseLink
Use @CacheInterceptor
on an entity to intercept all EclipseLink cache access to the entity instead of responding to cache operations through an event.
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 |
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.
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.
For more information, see:
Understanding EclipseLink
Oracle Coherence Integration Guide for Oracle TopLink with Coherence Grid
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.
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 For a OneToMany using a |
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:
DDL generation: If DDL generation is used, the generated constraint will include the cascade deletion option.
Entity: Remove will not execute SQL for deletion from secondary or joined inheritance tables (as constraint will handle deletion).
OneToOne: If the mapping uses cascading or orphanRemoval, SQL will not be executed to delete target object.
OneToMany: If the mapping uses cascading or orphanRemoval, SQL will not be executed to delete target objects.
ManyToMany: SQL will not be executed to delete from the join table.
ElementCollection: SQL will not be executed to delete from the collection table.
Cache: Cascaded objects will still be removed from the cache and persistence context.
Version locking: Version will not be verified on deletion of cascaded object.
Events: Deletion events may not be executed on the cascaded objects if the objects are not loaded.
Cascading: The remove operation should still be configured to cascade in the mapping if using CascadeOnDelete.
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
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.
Table 2-9 describes this annotation's elements.
Table 2-9 @ChangeTracking Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The change tracking policy to use:
|
|
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.
Note:
When using change tracking withATTRIBUTE
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.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");
For more information, see:
"Enhancing Performance" in Solutions Guide for EclispeLink
Use @ClassExtractor
to define a custom class indicator in place of providing a discriminator column.
Table 2-10 describes this annotation's elements.
Table 2-10 @ClassExtractor Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the class extractor to apply to the entity's descriptor |
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
.
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.
Use @CloneCopyPolicy
to specify an org.eclipse.persistence.descriptors.copying.CloneCopyPolicy
on an Entity.
Table 2-11 describes this annotation's elements.
Table 2-11 @CloneCopyPolicy Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The method that will be used to create a clone for comparison with EclispeLink's |
|
|
(Optional) The |
Note:
You must specify either amethod
or workingCopyMenthod
.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.
Example 2-25 and Example 2-26 show several examples of the @CloneCopyPolicy
annotation and <clone-copy-policy>
XML element, respectively.
For more information, see:
Understanding EclipseLink
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.
Table 2-12 describes this annotation's elements.
Table 2-12 @CompositeMember Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The name of a target composite member persistence unit to which element table belongs (if differs from source composite member persistence unit |
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.
You can configure the CompositeMember
using annotations or the eclipselink-orm.xml
file, as shown in these examples.
For more information, see:
"Using Multiple Databases with a Composite Persistence Unit" in Solutions Guide for EclispeLink
Use @ConversionValue
to specify the database and object values for an ObjectTypeConverter
.
Table 2-13 describes this annotation's elements.
Table 2-13 @ConversionValue Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The database value |
|
|
(Required) The object value |
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.
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>
Use @Convert
to specify that a named converter should be used with the corresponding mapped attribute.
Table 2-14 describes this annotation's elements.
Table 2-14 @Convert Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The |
|
The @Convert
has the following reserved names:
serialized – Places the org.eclipse.persistence.mappings.converters.SerializedObjectConverter
on the associated mapping.
class-instance – Uses an ClassInstanceConverter
on the associated mapping. When using a ClassInstanceConverter
, the database representation is a String
representing the Class name and the object-model representation is an instance of that class built with a no-args constructor
none – Does not place a converter on the associated mapping.
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;
}
...
}
For more information, see:
Understanding EclipseLink
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.
Table 2-15 describes this annotation's elements.
Table 2-15 @Converter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The |
none |
|
The class of your converter. This class must implement the |
none |
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:
@Convert
@Enumerated
@Lob
@Temporal
Serialized (automatic)
Specify the converters on the following classes:
@Entity
@MappedSuperclass
@Embeddable
Use the converters with the following mappings:
@Basic
@Id
@Version
@ElementCollection
An exception is thrown if a converter is specified with any other type of mapping annotation.
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.
For more information, see:
Understanding EclipseLink
Use @Converters
annotation to define multiple @Converter
elements.
Table 2-16 describes this annotation's elements.
Table 2-16 @Converters Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of converters |
See "@Converter" for an example of this annotation.
Use @CopyPolicy
to set an org.eclipse.persistence.descriptors.copying.CopyPolicy
on an entity to produce a copy of the persistent element.
Table 2-17 describes this annotation's elements.
Table 2-17 @CopyPolicy Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The class of the copy policy. The class must implement |
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.
For more information, see:
Understanding EclipseLink
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.
Table 2-18 describes this annotation's elements.
Table 2-18 @Customizer Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the descriptor customizer to apply to the entity's descriptor |
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.
Note:
A@Customizer
is not inherited from its parent classes.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.
For more information, see:
"Binding JPA Entities to XML" in Solutions Guide for EclispeLink
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.
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.
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.
Use @DiscriminatorClass
with a @VariableOneToOne
annotation to determine which entities will be added to the list of types for the mapping.
Table 2-19 describes this annotation's elements.
Table 2-19 @DiscriminatorClass Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The discriminator to be stored in the database |
|
value |
(Required) The class to be instantiated with the |
The @DiscriminatorClass
annotation can be specified only within a @VariableOneToOne
mapping.
See "@VariableOneToOne" for an example of a variable one-to-one mapping with @DiscriminatorClass
.
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.
Example 2-40 shows how to use the @ExcludeDefaultMapping
annotation.
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.
Table 2-20 describes this annotation's elements.
Table 2-20 @ExistenceChecking Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Set the existence checking type:
|
|
You can specify @ExistenceChecking
on an Entity or MappedSuperclass.
EclipseLink supports the following existence checking types:
ASSUME_EXISTENCE
– If the object's primary key does not include null
then it must exist. You may use this option if the application guarantees or does not care about the existence check.
ASSUME_NON_EXISTENCE
– Assume that the object does not exist. You may use this option if the application guarantees or does not care about the existence check. This will always force an INSERT
operation.
CHECK_CHACHE
– If the object's primary key does not include null
and it is in the cache, then it must exist.
CHECK_DATABASE
– Perform a SELECT
on the database.
Example 2-41 shows how to use this annotation.
For more information, see:
"Enhancing Performance" in Solutions Guide for EclispeLink
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.
Table 2-21 describes this annotation's elements.
Table 2-21 @FetchAttribute Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Name of the fetch attribute |
EclipseLink provides two types of fetch groups:
Pre-defined fetch groups at the Entity or MappedSuperclass level
Dynamic (use case) fetch groups at the query level
You should extensively review your use cases when using fetch groups. In many cases, additional round-trips will offset any gains from deferred loading.
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;
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.
Table 2-22 describes this annotation's elements.
Table 2-22 @FetchGroup Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The list of attributes to fetch |
none |
|
(Required) The fetch group name |
none |
|
(Optional) Indicates whether all relationship attributes specified in the fetch group should be loaded. |
|
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:
Pre-defined fetch groups at the Entity or MappedSuperclass level
Dynamic (use case) fetch groups at the query level
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.
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.
Use @FetchGroups
to define a group of @FetchGroup
.
Table 2-23 describes this annotation's elements.
Table 2-23 @FetchGroups Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of fetch groups ( |
You can specify @FetchGroups
on an Entity or MappedSuperclass.
You can also enable or disable fetch groups through weaving for the persistence unit.
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");
Use @Field
to define a structured data type's field name for an object mapped to NoSql data.
Table 2-24 describes this annotation's elements.
Table 2-24 @Field Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The data type's name of the field |
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.
See "@NoSql" for an example of the @Field
annotation.
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.
Table 2-25 describes this annotation's elements.
Table 2-25 @HashPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the partition policy. The name must be unique within the persistence unit. |
|
|
(Required) The database column or query parameter by which to partition queries |
|
|
(Optional) List of connection pool names across which to partition |
All defined pools in the ServerSession |
|
(Optional) Specify if queries that do not contain the partition hash should be sent to every database and union the result. |
False |
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:
Sent to all servers and unioned
or
Handled based on the session's default behavior.
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.
See "@Partitioned" for an example of partitioning with EclipseLink.
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.
Table 2-26 describes this annotation's elements.
Table 2-26 @Index Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The catalog of the |
Default catalog |
|
(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. |
j |
(Optional) The name of the |
|
|
(Optional) The schema of the |
Default schema |
|
(Optional) The table to define the index on; defaults to entities primary table. |
The entity's primary table. |
|
(Optional) Specify whether the index is unique or non-unique. |
|
Use @Index
annotation to index any attributes or columns that will commonly be used in queries.
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.
Use @Indexes
to define a set of database indexes for an Entity.
Table 2-27 describes this annotation's elements.
Table 2-27 @Indexes Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
An array of database indexes |
See "@Index" for an example of using the @Index
annotation.
Use @InstantiationCopyPolicy
to set an org.eclipse.persistence.descriptors.copying.InstantiationCopyPolicy
on an Entity.
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:
When using weaving.internal (and field access), EclipseLink generates a specialized clone method to copy objects.
Without weaving, EclipseLink uses instantiation to copy objects.
You can specify @InstantiationCopyPolicy
on an Entity, MappedSuperclass, or Embeddable entity.
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.
Use the @JoinFetch
annotation to enable the joining and reading of the related objects in the same query as the source object.
Note:
You should set join fetching at the query level, as not all queries require joining.Table 2-28 describes this annotation's elements.
Table 2-28 @JoinFetch Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Set this attribute to the The following are the valid values for the
|
|
You can specify the @JoinFetch
annotation for the following mappings:
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
@ElementCollection
Alternatively, you can use batch fetching which is more efficient, especially for collection relationships.
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.
For more information, see:
Understanding EclipseLink
"Enhancing Performance" in Solutions Guide for EclispeLink
Use @JoinField
to define a structured data type's foreign key field for an object mapped to NoSql data.
Table 2-29 describes this annotation's elements.
Table 2-29 @JoinField Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The name of the foreign key/ID reference field in the source record |
|
|
(Optional) The name of the ID field in the target record |
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.
Use @JoinFields
to define a set of @JoinField
annotations on a relationship.
Table 2-30 describes this annotation's elements.
Table 2-30 @JoinFields Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
An array of join fields |
See "@JoinField" for an example of using the @Index
annotation.
Use @MapKeyConvert
to specify a named converter to be used with the corresponding mapped attribute key column.
Table 2-31 describes this annotation's elements.
Table 2-31 @MapKeyConvert Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Name of the converter to use:
|
none |
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:
serialized
: Will use a SerializedObjectConverter
on the associated mapping. When using a SerializedObjectConverter
the database representation is a binary field holding a serialized version of the object and the object-model representation is a the actual object
class-instance
: Will use an ClassInstanceConverter on the associated mapping. When using a ClassInstanceConverter the database representation is a String representing the Class name and the object-model representation is an instance of that class built with a no-args constructor
none
- Will place no converter on the associated mapping. This can be used to override a situation where either another converter is defaulted or another converter is set.
If you do not use one of these reserved names, you must define a custom converter, using the @Converter
annotation.
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>
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.
Table 2-32 describes this annotation's elements.
Table 2-32 @Multitenant Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Indicates if the database requires the tenant criteria to be added to the |
|
|
Specifies the multitenant strategy to use: |
|
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 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.
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.
Note:
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".
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.
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:
A table-per-tenant property to identify the user. This can be set per entity manager, or it can be set at the entity manager factory to isolate table-per-tenant per persistence unit.)
A tenant table discriminator to identify and isolate the tenant's tables from other tenants' tables. The discriminator types are SCHEMA
, SUFFIX
, and PREFIX
. For more information about tenant discriminator types, see "@TenantTableDiscriminator".
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.
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
:
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.
@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>
"Using Multitenancy" in Solutions Guide for EclispeLink
Multitenant Examples at http://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant
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.
Table 2-33 describes this annotation's elements.
Table 2-33 @Mutable Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Specifies if the mapping is mutable. |
true |
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.
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");
Use the @NamedPLSQLStoredFunctionQueries
annotation to define multiple NamedPLSQLStoredFunctionQuery
items.
Table 2-34 describes this annotation's elements.
Use the @NamedPLSQLStoredFunctionQuery
annotation to define queries that call Oracle PLSQL stored functions as named queries
Table 2-36 describes this annotation's elements.
Table 2-35 @NamedPLSQLStoredFunctionQuery Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the stored function |
|
|
(Required) The unique name that references this stored function query |
|
|
(Required) The return value of the stored function |
|
|
(Optional) Query hints |
|
|
(Optional) The parameters for the stored function |
|
|
(Optional) The name of the |
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.
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 { ...}
For more information, see:
Use the @NamedPLSQLStoredProcedureQueries
annotation to define multiple NamedPLSQLStoredProcedureQuery
items.
Table 2-36 describes this annotation's elements.
Table 2-36 @NamedPLSQLStoredProcedureQueries Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of named stored procedure query |
Example 2-68 shows how to use this annotation.
For more information, see:
"Stored Procedures" in Understanding EclipseLink
Oracle PL/SQL http://www.oracle.com/technetwork/database/features/plsql/index.html
Use the @NamedPLSQLStoredProcedureQuery
annotation to define queries that call Oracle PLSQL stored procedures as named queries.
Table 2-37 describes this annotation's elements.
Table 2-37 @NamedPLSQLStoredProcedureQuery Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the stored procedure |
|
|
(Required) The unique name that references this stored procedure query |
|
|
(Optional) The class of the result |
|
|
(Optional) Query hints |
|
|
(Optional) The parameters for the stored procedure |
|
|
(Optional) The name of the |
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.
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 { ...}
For more information, see:
"Stored Procedures" in Understanding EclipseLink
Oracle PL/SQL http://www.oracle.com/technetwork/database/features/plsql/index.html
Use the @NamedStoredFunctionQueries
annotation to define multiple NamedStoredFunctionQuery
items.
Table 2-38 describes this annotation's elements.
Table 2-38 @NamedStoredFunctionQueries Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of named stored procedure query |
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.
Use @NamedStoredFunctionQuery
to define queries that call stored functions as named queries.
Table 2-39 describes this annotation's elements.
Table 2-39 @NamedStoredFunctionQuery Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the stored function |
|
name |
(Required) The unique name that references this stored function query |
|
|
(Required) The return value of the stored function |
|
|
(Optional) Specifies if the stored function should be called by index or by name.
|
false |
|
(Optional) Query hints |
|
|
(Optional) The parameters for the stored function |
|
|
(Optional) The name of the SQLResultMapping |
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.
Use the @NamedStoredProcedureQueries
annotation to define multiple NamedStoredProcedureQuery
items.
Table 2-40 describes this annotation's elements.
Table 2-40 @NamedStoredProcedureQueries Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of named stored procedure query |
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.
For more information, see:
"Stored Procedures" in Understanding EclipseLink
Use the @NamedStoredProcedureQuery
annotation to define queries that call stored procedures as named queries.
Table 2-41 describes this annotation's elements.
Table 2-41 @NamedStoredProcedureQuery Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Unique name that references this stored procedure query |
|
|
(Required) Name of the stored procedure |
|
|
(Optional) Specifies if the stored procedure should be called by name.
|
|
|
(Optional) An array of query hints |
|
|
(Optional) Specifies if the stored procedure returns multiple result sets. This applies only for databases that support multiple result sets from stored procedures. |
|
|
(Optional) An array of parameters for the stored procedure |
|
|
(Optional) The class of the result |
|
|
(Optional) Name of the |
|
|
(Optional) Specifies if the stored procedure retainers a result set. This applies only for databases that support result sets from stored procedures. |
|
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>
For more information, see:
"Stored Procedures" in Understanding EclipseLink
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.
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.
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
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.
Table 2-42 describes this annotation's elements.
Table 2-42 @NoSql Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The name of the entities structure. The purpose of the
|
|
|
(Optional) The type structure (data format) in which the data is stored within the database:
|
XML |
The dataFormat
depends on the NoSQL platform used:
For MongoDB, use MAPPED
.
For Oracle NoSQL, use MAPPED
(for key/value data) or XML
(for a single XML document).
For XML files and XML messaging, use XML
.
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:
MongoDB
Oracle NoSQL
XML Files
JMS
Oracle AQ
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", }
For more information, see:
Oracle Coherence Integration Guide for Oracle TopLink with Coherence Grid
"Using Non-SQL Databases" in Understanding EclipseLink
"Using NoSQL Databases" in Understanding EclipseLink
"Using EclipseLink with Nonrelational Databases" in Solutions Guide for EclispeLink
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.
Table 2-43 describes this annotation's elements.
Table 2-43 @ObjectTypeConverter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Set this attribute to the |
none |
|
(Optional) Set this attribute to the type stored in the database. |
|
|
(Optional) Set the value of this attribute to the type stored on the entity. |
|
|
Set the value of this attribute to the array of conversion values (instances of |
none |
|
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 |
Footnote 1 The default is inferred from the type of the persistence field or property.
EclipseLink also includes @TypeConverter
and @StructConverter
converters.
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.
Use @ObjectTypeConverters
to define multiple ObjectTypeConverter
items.
Table 2-44 describes this annotation's elements.
Table 2-44 @ObjectTypeConverters Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of |
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.
Use @OptimisticLocking
to specify the type of optimistic locking EclipseLink should use when updating or deleting entities.
Table 2-45 describes this annotation's elements.
Table 2-45 @OptimisticLocking Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(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 |
|
|
(Optional) Specify a list of columns that will be optimistically locked. This element is required when |
|
|
(Optional) The type of optimistic locking policy to use:
|
|
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.
Use the @OracleArray
annotation to define an Oracle database VARRAY
type, which you can use within PLSQL procedure calls.
Table 2-46 describes the annotation's elements.
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{...}
Please review this example and let me know what needs to be changed.
Use the @OracleArrays
annotation to define multiple VARRAY
types.
Table 2-47 describes the annotation's elements.
See "@OracleArray" for an example of how to use this annotation.
Use the @OracleObject
annotation to define an Oracle database OBJECT
type, which you can use within PLSQL procedure calls.
Table 2-48 describes the annotation's elements.
Table 2-48 @OracleObject Annotation Elements
Element | Description | Default |
---|---|---|
name |
(Required) The name of the |
|
javaType |
(Optional) The Java type to which you want to map the |
void |
fields |
(Required) Defines the parameter fields in the record type |
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{...}
Use the @OracleObjects
annotation to define multiple Oracle OBJECT
types.
Table 2-49 describes the annotation's elements.
See "@OracleObject" for an example of how to use this annotation.
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}
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:
|
|
When using @OrderCorrection
, you can specify how EclipseLink should handle invalid list orders:
EXCEPTION
– When OrderCorrectionType=EXCEPTION
, EclipseLink will not correct the list. Instead, EclipseLink will throw a QueryException
with error code QueryException.LIST_ORDER_FIELD_WRONG_VALUE
For example, given the following list of three objects in the database:
{null, objectA}; {2, objectB}, {5, ObjectC};
When read into the application, EclipseLink will throw an exception.
READ
– When OrderCorrectionType=READ
, EclipseLink corrects the list read into application, but does not retain any information about the invalid list order that remains in the database. Although this is not an issue in read-only uses of the list, if the list is modified and then saved into the database, the order will most likely differ from the cache and be invalid.
The READ
mode is used as the default when the mapped attribute is not a List
.
For example, given the following list of three objects in the database:
{null, objectA}; {2, objectB}, {5, ObjectC}
When read as a list: {objectA, objectB, objectC}
When adding a new element to the list: {objectA, objectB, objectC, objectD}
When saving the updated list to the database: {null, objectA}, {2, objectB}, {5, objectC}, {3, objectD}
When reading the list again: {objectA, objectB, objectD, objectC}
READ_WRITE
– When OrderCorrectionType=READ_WRITE
, EclipseLink corrects the order of the list read into application and remembers the invalid list order left in the database. If the list is updated and saved to the database, the order indexes are saved ensuring that the list order in the data base will be exactly the same as in cache (and therefore valid).
The READ_WRITE
mode is used as the default when the mapped attribute is either a List
or Vector
(that is, it is assignable from the EclipseLink internal class IndirectList
). In JPA, if the mode is not specified, READ_WRITE
is used by default.
For example, given the following list of three objects in the database:
{null, objectA}; {2, objectB}, {5, ObjectC}
When read as a list: {objectA, objectB, objectC}
When adding a new element to the list: {objectA, objectB, objectC, objectD}
When saving the updated list to the database: {0, objectA}, {1, objectB}, {2, objectC}, {3, objectD}
When reading the list again: {objectA, objectB, objectC, objectD}
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.
Use @Partitioned
to specify a partitioning policy to use for an Entity or relationship.
Table 2-51 describes this annotation's elements.
Table 2-51 @Partitioned Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Name of the partitioning policy |
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.
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:
@HashPartitioning
: Partitions access to a database cluster by the hash of a field value from the object, such as the object's ID, location, or tenant. The hash indexes into the list of connection pools/nodes. All write or read request for objects with that hash value are sent to the same server. If a query does not include the hash field as a parameter, it can be sent to all servers and unioned, or it can be left to the session's default behavior.
@PinnedPartitioning
: Pins requests to a single connection pool/node. This allows for vertical partitioning.
@RangePartitioning
: Partitions access to a database cluster by a field value from the object, such as the object's ID, location, or tenant. Each server is assigned a range of values. All write or read requests for objects with that value are sent to the same 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.
@ReplicationPartitioning
: Sends requests to a set of connection pools/nodes. This policy is for replicating data across a cluster of database machines. Only modification queries are replicated.
@RoundRobinPartitioning
: Sends requests in a round-robin fashion to the set of connection pools/nodes. It is for load balancing read queries across a cluster of database machines. It requires that the full database be replicated on each machine, so it does not support partitioning. The data should either be read-only, or writes should be replicated.
@UnionPartitioning
: Sends queries to all connection pools and unions the results. This is for queries or relationships that span partitions when partitioning is used, such as on a ManyToMany
cross partition relationship.
@ValuePartitioning
: Partitions 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 requests for objects with that value are sent to the same server. If a query does not include the field as a parameter, then it can be sent to all servers and unioned, or it can be left to the session's default behavior.
@Partitioning
: Partitions access to a database cluster by a custom partitioning policy. A PartitioningPolicy class must be provided and implemented.
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:
Partition policy should not enable replication, as database cluster makes data available to all nodes.
Partition policy should not use unions, as database cluster returns the complete query result from any node.
A data source and EclipseLink connection pool should be defined for each node in the cluster.
The application's data access and data partitioning should be designed to have each transaction only require access to a single node.
Usage of an exclusive connection for an EntityManager is recommended to avoid having multiple nodes in a single transaction and avoid 2-phase commit.
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; ... }
For more information, see:
Use @Partitioning
to configure a custom PartitioningPolicy
.
Table 2-52 describes this annotation's elements.
Table 2-52 @Partitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Name of the partition policy. Names must be unique for the persistence unit. |
|
|
(Required) Full |
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.
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;
}
}
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).
Table 2-53 describes this annotation's elements.
Table 2-53 @PinnedPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Connection pool name to which to pin queries |
|
|
Name of the partition policy. Names must be unique for the persistence unit. |
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.
See "Using Partitioning" for an example of partitioning with EclipseLink.
Use @PLSQLParameter
within a NamedPLSQLStoredProcedureQuery
or PLSQLRecord
annotation.
Table 2-54 describes this annotation's elements.
Table 2-54 @PLSQLParameter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The query parameter name |
|
|
(Optional) The direction of the stored procedure parameter:
|
|
|
(Optional) Database data type for the parameter. This either one of the type constants defined in |
|
|
(Optional) Maximum length of the field value |
|
|
(Optional) Stored procedure parameter name |
|
|
(Optional) Specify if the parameter is required, or optional and defaulted by the procedure. |
|
|
(Optional) Maximum precision value |
|
|
(Optional) Maximum precision value |
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.
See "@NamedPLSQLStoredProcedureQuery" for an example using the @PLSQLParameter
annotation.
Use @PLSQLRecord
to define a database PLSQL RECORD
type for use within PLSQL procedures.
Table 2-55 describes this annotation's elements.
Table 2-55 @PLSQLRecord Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the table in the database |
|
|
(Required) Name of the database |
|
|
(Required) The fields in the record type |
|
|
(Optional) The class of the object type. You must map this class with the |
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.
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 { ... }
For more information, see:
"Stored Procedures" in Understanding EclipseLink
Oracle PL/SQL http://www.oracle.com/technetwork/database/features/plsql/index.html
Use @PLSQLRecords
to define multiple PLSQLRecord
.
Table 2-56 describes this annotation's elements.
Table 2-56 @PLSQLRecords Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of named PLSQL records |
See "@PLSQLRecord" for an example of how to use this annotation.
For more information, see:
"Stored Procedures" in Understanding EclipseLink
Oracle PL/SQL http://www.oracle.com/technetwork/database/features/plsql/index.html
Use the @PLSQLTable
annotation to define a database PLSQL TABLE
type, which you can use within PLSQL procedure calls.
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 |
|
nestedType |
(Required) The type of table, e.g. |
|
javaType |
(Optional) The Java |
|
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 ( |
|
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{...}
Use the @PLSQLTables
annotation to define mutiple PLSQL tables.
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 |
See "@PLSQLTable" for examples of how to use this annotation.
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.
Table 2-59 describes this annotation's elements.
Table 2-59 @PrimaryKey Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(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:
|
|
|
(Optional) Directly specifies the primary key columns. This can be used instead of |
|
|
(Optional) Configures what ID validation is done:
By default |
|
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.
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.
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.
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.
When indicating that a relationship is privately owned, you are specifying the following:
If the source of a privately owned relationship is deleted, then EclipseLink will delete the target. This is equivalent of setting @CascadeOnDelete.
If you remove the reference to a target from a source, then EclipseLink will delete the target.
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.
Note:
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.
Example 2-96 shows using @PrivateOwned
to specify Employee
field phoneNumbers.
.
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.
Table 2-60 describes this annotation's elements.
Table 2-60 @Properties Annotation Elements
Annotation Element | Description | Default |
---|---|---|
Property |
Array of |
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.
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.
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.
Table 2-61 describes this annotation's elements.
Table 2-61 @Property Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Name of the property |
|
|
(Required) String representation of the property |
|
|
(Optional) Property value type, converted to valueType by |
|
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.
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.
Use @QueryRedirectors
to intercept EclipseLink queries for pre- and post-processing, redirection, or performing some side effect such as auditing.
Table 2-62 describes this annotation's elements.
Table 2-62 @QueryRedirectors Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
This |
|
|
A Default |
|
insert |
A Default |
|
readAll |
A Default For users executing a JPA Query through the |
|
|
A Default For users executing a JPA Query through the |
|
|
A Default For users executing a JPA Query that contains aggregate functions or selects multiple entities this is the redirector that will be invoked |
|
|
A Default |
|
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 TopLink Grid to redirect queries to the Coherence grid.
Example 2-97 shows how to use this annotation.
Use @RangePartition
to create a specific range partition for a connection pool. Values within the range will be routed to the specified connection pool.
Table 2-63 describes this annotation's elements.
Table 2-63 @RangePartition Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The connection pool to which to route queries for the specified range |
|
|
The |
|
|
The |
See "Using @RangePartitioning" for an example of partitioning with EclipseLink.
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.
Table 2-64 describes this annotation's elements.
Table 2-64 @RangePartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The name of the partition policy; must be unique for the persistence unit. |
|
|
(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. |
|
|
(Required) List of connection pool names to partition across |
|
|
The type of the start and end values |
|
|
Defines if queries that do not contain the partition field should be sent to every database and have the result unioned. |
|
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.
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>
Use @ReadOnly
to specify that a class is read-only.
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).
Note:
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.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.
Use @ReadTransformer
with Transformation mappings to define the transformation of the database column values into attribute values (unless the mapping is write-only).
Table 2-65 describes this annotation's elements.
Table 2-65 @ReadTransformer Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
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 The class will be instantiated, its |
|
Note:
You must specify either amethod
or transformerClass
, but not both.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
).
See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation
with a Transformation mapping.
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.
Table 2-66 describes this annotation's elements.
Table 2-66 @ReplicationPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The name of the partition policy; must be unique for the persistence unit |
|
|
List of connection pool names to replicate across |
All defined pools in the |
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.
See "Using Partitioning" for an example of partitioning with EclipseLink.
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.
Note:
Returning is only supported with an Oracle Database and requires anINSERT RETURNING
clause.
To use returning with other databases, a stored procedure with output parameters is used for the insert query.
Table 2-67 describes this annotation's elements.
Table 2-67 @ReturnInsert Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) If specified (true), the mapping field will be excluded from the |
false |
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.
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.
Note:
Returning is only supported with an Oracle Database and requires anINSERT RETURNING
clause.
To use returning with other databases, a stored procedure with output parameters is used for the insert query.
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.
Use @RoundRobinPartitioning
to send requests in a "round robin" fashion to the set of connection pools.
Table 2-68 describes this annotation's elements.
Table 2-68 @RoundRobinPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Name of the partition policy. Names must be unique for the persistence unit. |
|
|
(Optional) List of connection pool names to load balance across |
All defined pools in the |
|
(Optional) This allows for a set of database to be written to and kept in sync, and have reads load-balanced across the databases. |
|
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.
See "@Partitioned" for an example of partitioning with EclipseLink.
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.
Table 2-69 describes this annotation's elements.
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).
Note:
Currently, no default implementation of theSerializedObjectPolicy
interface is available. You must provide this class.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. .
Use @StoredProcedureParameter
within a NamedStoredProcedureQuery
annotation.
Table 2-70 describes this annotation's elements.
Table 2-70 @StoredProcedureParameter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The query parameter name |
|
|
(Optional) The direction of the stored procedure parameter:
|
|
|
(Optional) JDBC type code. This depends on the type returned from the procedure. |
|
|
(Optional) JDBC type name. This may be required for |
|
|
(Optional) Stored procedure parameter name |
|
|
(Optional) Specify if the parameter is required, or optional and defaulted by the procedure. |
|
|
(Optional) Type of Java class desired back from the procedure. This depends on the |
|
See "@NamedStoredProcedureQuery" for an example using the @StoredProcedureParameter
annotation.
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.
Table 2-71 describes this annotation's elements.
Table 2-71 @Struct Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The database name of the database structure type |
|
|
(Optional) Defines the order of the fields contained in the database structure type. |
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.
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>
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.
Note:
Unlike other converters,@StructConverter
has its own interface.Table 2-72 describes this annotation's elements.
Table 2-72 @StructConverter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The |
none |
|
The converter class as a |
none |
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
.
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.
Use @StructConverters
to define multiple @StructConverter
annotations.
Table 2-73 describes this annotation's elements.
Table 2-73 @StructConverters Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of struct converter |
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.
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.
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.
Example 2-114 shows how to use the @Structure
annotation. See Example 2-109 to an example of using @Struct
to map the target.
You can also define structure mappings in the eclipselink-orm.xml
file by using the <structure>
element.
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.
Table 2-74 describes this annotation's elements.
Table 2-74 @TenantDiscriminatorColumn Properties
Annotation Element | Description | Default |
---|---|---|
|
(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. |
|
(Optional) The name of the context property to apply to the tenant discriminator column |
|
|
(Optional) The type of object/column to use as a class discriminator |
|
|
(Optional) The column length for String-based discriminator types |
The column length for String-based discriminator types. Ignored for other discriminator types. |
|
(Optional) The name of column to be used for the tenant discriminator |
|
|
Specifies that the tenant discriminator column is part of the primary key of the tables. |
|
|
(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. |
To configure single-table multi-tenancy, you must specify both of the following:
Annotate the entity or mapped superclass to use single-table multi-tenancy, using the @Multitenant
annotation, for example:
@Entity @Table(name=”EMP”) @Multitenant(SINGLE_TABLE)
SINGLE_TABLE
states that the table or tables (Table
and SecondaryTable
) associated with the given entity can be shared among tenants.
Note:
The@Table
annotation is not required, because the discriminator column is assumed to be on the primary table. However, if the discriminator column is defined on a secondary table, you must identify that table using @SecondaryTable
.Specify the column or columns to be used as the discriminator column, using the @TenantDiscriminatorColumn
annotation, for example:
@Entity @Table(name=”EMP”) @Multitenant(SINGLE_TABLE) @TenantDiscriminatorColumn(name = ”TENANT_ID”)
You can specify multiple discriminator columns by using the @TenantDiscriminatorColumns
annotation, for example:
@Entity @Table(name = "EMPLOYEE") @Multitenant(SINGLE_TABLE) @TenantDiscriminatorColumns({ @TenantDiscriminatorColumn(name = "TENANT_ID") @TenantDiscriminatorColumn(name = "TENANT_CODE" contextProperty="eclipselink.tenant-code")})
The following characteristics apply to discriminator columns:
On persist, the values of tenant discriminator columns are populated from their associated context properties.
Tenant discriminator columns are application definable. That is, the discriminator column is not tied to a specific column for each shared entity table. You can use TENANT_ID
, T_ID
, etc.
There is no limit on how many tenant discriminator columns an application can define.
Any name can be used for a discriminator column.
Tenant discriminator column(s) must always be used with @Multitenant(SINGLE_TABLE
). You cannot specify the tenant discriminator column(s) only.
Generated schemas can include specified tenant discriminator columns.
Tenant discriminator columns can be mapped or unmapped:
When a tenant discriminator column is mapped, its associated mapping attribute must be marked as read only. With this restriction in place, a tenant discriminator column cannot be part of the entity identifier; it can only be part of the primary key specification on the database.
Both mapped and unmapped properties are used to form the additional criteria when issuing a SELECT
query.
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:
Multi-tenant metadata can be applied only at the root level of the inheritance hierarchy when using a SINGLE_TABLE
or JOINED
inheritance strategy.
You can also specify multi-tenant metadata within a TABLE_PER_CLASS
inheritance hierarchy. In this case, every entity has its own table, with all its mapping data (which is not the case with SINGLE_TABLE
or JOINED
strategies). Consequently, in the TABLE_PER_CLASS
strategy, some entities of the hierarchy may be multi-tenant, while others may not be. The other inheritance strategies can only specify multi-tenancy at the root level, because you cannot isolate an entity to a single table to build only its type.
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>
"Using Multitenancy" in Solutions Guide for EclispeLink
Specify multiple discriminator columns for single-table multitenancy by using the @TenantDiscriminatorColumns
annotation to contain multiple @TenantDiscriminatorColumn
annotations.
Table 2-75 describes this annotation's elements.
Table 2-75 @TenantDiscriminatorColumns Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) One or more |
none |
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
.
@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
.
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.
Table 2-76 describes this annotation's elements.
Table 2-76 @TenantTableDiscriminator Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Name of the context property to apply to as tenant table discriminator |
|
|
(Optional) Type of tenant table discriminator to use with the tables of the persistence unit:
|
|
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:
Schema: Applies the tenant table discriminator as a schema to all multitenant tables. This strategy requires appropriate database provisioning.
Suffix: Applies the tenant table discriminator as a suffix to all multitenant tables. This is the default strategy.
Prefix: Applies the tenant table discriminator as a prefix to all multitenant tables.
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".
The following example shows a SCHEMA
-type table discriminator.
"Using Multitenancy" in Solutions Guide for EclispeLink
Multitenant Examples at http://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant
Use @TimeOfDay
to specify a specific time of day using a Calendar
instance which is to be used within an @Cache
annotation.
Table 2-77 describes this annotation's elements.
Table 2-77 @TimeOfDay Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Hour of the day |
|
|
(Optional) Millisecond of the day |
|
|
(Optional) Minute of the day |
|
|
(Optional) Second of the day |
|
|
For internal use – do not modify |
|
See "@Cache" for examples of using @TimeOfDay
.
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).
Table 2-78 describes this annotation's elements.
Table 2-78 @Transformation Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Defines whether the value of the field or property should be lazily loaded or must be eagerly fetched.
|
|
|
(Optional) A hint as to whether the value of the field or property may be |
|
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
).
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>
Use @TypeConverter
to modify data values during the reading and writing of a mapped attribute.
Table 2-79 describes this annotation's elements.
Table 2-79 @TypeConverter Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) The |
none |
|
(Optional) The |
|
|
(Optional) The |
|
Footnote 1 The default is inferred from the type of the persistence field or property.
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.
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.
Use @TypeConverters
to define multiple TypeConverter
elements.
Table 2-80 describes this annotation's elements.
Table 2-80 @TypeConverters Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) An array of type converter |
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.
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.
Table 2-81 describes this annotation's elements.
Table 2-81 @UnionPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Name of the partition policy. Names must be unique for the persistence unit. |
|
|
List of connection pool names to load balance across |
Defaults to all defined pools in the |
|
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. |
|
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.
See "Using Partitioning" for an example of partitioning with EclipseLink.
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).
Table 2-82 describes this annotation's elements.
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.
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.
Table 2-81 describes this annotation's elements.
Table 2-83 @UnionPartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
Name of the partition policy. Names must be unique for the persistence unit. |
|
|
List of connection pool names to load balance across |
Defaults to all defined pools in the |
|
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. |
|
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.
See "Using Partitioning" for an example of partitioning with EclipseLink.
Use @ValuePartition
to represent a specific value partition that will be routed to a specific connection pool.
Table 2-84 describes this annotation's elements.
Table 2-84 @ValuePartition Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
The connection pool to which to route queries to for the |
|
|
The |
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>
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.
Table 2-85 describes this annotation's elements.
Table 2-85 @ValuePartitioning Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Required) Name of the partition policy. Names must be unique for the persistence unit. |
|
|
(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. |
|
|
(Required) Store the value partitions. Each partition maps a value to a |
|
|
(Optional) The default connection pool is used for any unmapped values |
|
|
(Optional) The |
|
|
(Optional) Defines if queries that do not contain the partition field should be sent to every database and have the result unioned. |
|
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.
See "Using Partitioning" for an example of partitioning with EclipseLink.
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.
Table 2-86 describes this annotation's elements.
Table 2-86 @VariableOneToOne Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Array of operations that must be cascaded to the target of the association |
|
|
(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 If If |
|
(Optional) The discriminator column that contains the type identifiers |
|
|
(Optional) Specify how the value of the field or property should be loaded:
|
|
|
(Optional) Specify if the association is optional. |
|
|
(Optional) Specify if interface class that is the target of this mapping. |
|
|
(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. |
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>
Use @VirtualAccessMethods
to specify that a specific class contains virtual methods.
Table 2-87 describes this annotation's elements.
Table 2-87 @VirtualAccessMethods Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) Name of the If |
|
set |
(Optional) Name of the If |
|
Use the @VirtualAccessMethods
annotation to define access methods for mappings with in which accessType
=VIRTUAL.
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.
For more information, see:
"Making JPA Entities and JAXB Beans Extensible" in Solutions Guide for EclispeLink
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.
Table 2-88 describes this annotation's elements.
Table 2-88 @WriteTransformer Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
(Optional) The column into which the value should be written If a single |
|
|
(Optional) The Note: To support DDL generation and returning policy, the method should be defined to return a particular type, not just an The method may require |
|
|
(Optional) User-defined class that implements the Note: To support DDL generation and returningpolicy, the method |
|
Note:
You must specify eithertransformerClass
or method
, but not both.You cannot define a @WriteTransforme
r 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
.
See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation
with a Transformation mapping.
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.
Table 2-89 describes this annotation's elements.
Table 2-89 @WriteTransformers Annotation Elements
Annotation Element | Description | Default |
---|---|---|
|
An array of |
See "Using @Transformation Annotation" for an example of how to use the @WriteTransformer annotation
with a Transformation mapping.