Using EclipseLink JPA Extensions (ELUG)
From Eclipsepedia
Contents[show] |
The Java Persistence API (JPA), part of the Java Enterprise Edition 5 (Java EE 5) EJB 3.0 specification, greatly simplifies Java persistence and provides an object relational mapping approach that allows you to declaratively define how to map Java objects to relational database tables in a standard, portable way that works both inside a Java EE 5 application server and outside an EJB container in a Java Standard Edition (Java SE) 5 application.
EclipseLink JPA provides extensions to what is defined in the JPA specification. These extensions come in persistence unit properties, query hints, annotations, EclipseLink own XML metadata, and custom API.
This section explains where and how you use the extensions to customize JPA behavior to meet your application requirements.
For more information, see the following:
- EclipseLink API Reference
- JSR-220 Enterprise JavaBeans v.3.0 Java Persistence API specification
- Java EE 5 SDK JPA Javadoc
Using EclipseLink JPA Extensions for Mapping
EclipseLink defines the following mapping metadata annotations (in addition to JPA-defined ones):
EclipseLink persistence provider searches mapping annotations in the following order:
EclipseLink persistence provider applies the first annotation that it finds; it ignores other mapping annotations, if specified. In most cases, EclipseLink does not log warnings or throw exceptions for duplicate or incompatible mapping annotations.
If EclipseLink persistence provider does not find any of the mapping annotations from the preceding list, it applies the defaults defined by the JPA specification: not necessarily the @Basic annotation.
How to Use the @BasicCollection Annotation
You can use the @BasicCollection annotation to map an org.eclipse.persistence.mappings.DirectCollectionMapping, which stores a collection of simple types, such as String, Number, Date, and so on, in a single table. The table must store the value and the foreign key to the source object.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface BasicCollection { ... }
Use the @BasicCollection annotation in conjunction with a @CollectionTable annotation. You can also use it in conjunction with @Convert to modify the data value(s) during reading and writing of the collection, as well as with the @JoinFetch Annotation.
This table lists attributes of the @BasicCollection annotation.
Attributes of the @BasicCollection Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
fetch |
The javax.persistence.FetchType enumerated type that defines whether EclipseLink should lazily load or eagerly fetch the value of the field or property. |
FetchType.LAZY |
optional |
valueColumn |
The name of the value column (javax.persistence.Column) that holds the direct collection data. |
@ColumnNote: EclipseLink persistence provider sets the default to the name of the field or property. |
optional |
Note: If you specify @BasicCollection on an attribute of type Map, EclipseLink will throw an exception: the type must be Collection, Set or List. If you specify the fetch type as LAZY, Collection implementation classes will also not be valid. |
This example shows how to use the @BasicCollection annotation to specify Employee field responsibilities.
Usage of the @BasicCollection Annotation
@Entity public class Employee implements Serializable{ ... @BasicCollection ( fetch=FetchType.EAGER, valueColumn=@Column(name="DESCRIPTION") ) @CollectionTable ( name="RESPONS", primaryKeyJoinColumns= {@PrimaryKeyJoinColumn(name="EMPLOYEE_ID", referencedColumnName="EMP_ID")} ) public Collection getResponsibilities() { return responsibilities; } ... }
To further customize your mapping, use the DirectCollectionMapping API.
How to Use the @BasicMap Annotation
You can use the @BasicMap annotation to map an org.eclipse.persistence.mappings.DirectMapMapping, which stores a collection of key-value pairs of simple types, such as String, Number, Date, and so on, in a single table. The table must store the value and the foreign key to the source object.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface BasicMap { ... }
Use the @BasicMap annotation in conjunction with a @CollectionTable annotation, as well as with the @JoinFetch Annotation.
This table lists attributes of the @BasicMap annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
fetch |
Set this attribute to the javax.persistence.FetchType enumerated type to define whether EclipseLink persistence provider has to lazily load or eagerly fetch the value of the field or property. |
FetchType.LAZY |
optional |
keyColumn |
Set this attribute to the name of the data column (javax.persistence.Column) that holds the direct map key. |
<field-name>_KEY or <property-name>_KEY (in uppercase characters) |
required |
keyConverter |
Set this attribute to the key converter (java.eclipselink.annotations.Convert) |
@Convert – an equivalent of specifying @Convert("none") resulting in no converter added to the direct map key. |
optional |
valueColumn |
Set this attribute to the name of the value column (javax.persistence.Column) that holds the direct collection data. |
@Column |
optional |
valueConverter |
Set this attribute to the value converter (java.eclipselink.annotations.Convert). |
@Convert – an equivalent of specifying @Convert("none") resulting in no converter added to the direct map key. |
optional |
Note: If you specify @BasicMap on an attribute of type Collection, EclipseLink will throw an exception: the type must be Map. If you specify the fetch type as LAZY, Map implementation classes are also not valid. |
This example shows how to use the @BasicMap annotation to specify Employee field licenses.
Usage of the @BasicMap Annotation
@Entity @Table(name="CMP3_EMPLOYEE") @TypeConverter( name="Integer2String", dataType=Integer.class, objectType=String.class ) public class Employee implements Serializable{ ... @BasicMap ( fetch=FetchType.EAGER, keyColumn=@Column(name="LICENSE"), keyConverter=@Convert("licenseConverter"), valueColumn=@Column(name="STATUS")), valueConverter=@Convert("Integer2String") ) @ObjectConverter( name="licenseConverter", conversionValues={ @ConversionValue(dataValue="AL", objectValue="Alcohol License"), @ConversionValue(dataValue="FD", objectValue="Food License"), @ConversionValue(dataValue="SM", objectValue="Smoking License"), @ConversionValue(dataValue="SL", objectValue="Site Licence")} ) @CollectionTable ( name="LICENSE", primaryKeyJoinColumns={@PrimaryKeyJoinColumn(name="REST_ID")} ) public Map<String> getLicenses() { return licenses; } ... }
To further customize your mapping, use the DirectMapMapping API.
How to Use the @CollectionTable Annotation
You can use the @CollectionTable annotation in conjunction with a @BasicCollection annotation (see How to Use the @BasicCollection Annotation) or the @BasicMap annotation (see How to Use the @BasicMap Annotation). If you do not specify the @CollectionTable, EclipseLink persistence provider will use the defaults.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface CollectionTable { ... }
This table lists attributes of the @CollectionTable annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the String name for your collection table. |
empty String |
optional |
catalog |
Set this attribute to the String name of the table's catalog. |
empty String |
optional |
schema |
Set this attribute to the String name of the table's schema. |
empty String |
optional |
primaryKeyJoinColumns |
Set this attribute to an array of javax.persistence.PrimaryKeyJoinColumn instances to specify a primary key column that is used as a foreign key to join to another table. If the source entity uses a composite primary key, you must specify a primary key join column for each field of the composite primary key. If the source entity uses a single primary key, you may choose to specify a primary key join column (optional). Otherwise, EclipseLink persistence provider will apply the following defaults:
If the source entity uses a composite primary key and you failed to specify the primary key join columns, EclipseLink will throw an exception. |
empty PrimaryKeyJoinColumn array |
optional |
uniqueConstraints |
Set this attribute to an array of javax.persistence.UniqueConstraint instances that you want to place on the table. These constraints are only used if table generation is in effect. |
empty UniqueConstraint array |
optional |
This example shows how to use the @CollectionTable annotation to specify Employee field responsibilities.
Usage of the @CollectionTable Annotation
@Entity public class Employee implements Serializable{ ... @BasicCollection ( fetch="LAZY", valueColumn=@Column(name="DESCRIPTION") ) @CollectionTable ( name="RESPONS", primaryKeyJoinColumns= {@PrimaryKeyJoinColumn(name="EMPLOYEE_ID", referencedColumnName="EMP_ID")} ) public Collection getResponsibilities() { return responsibilities; } ... }
How to Use the @PrivateOwned Annotation
Use the @PrivateOwned annotation in conjunction with a @OneToOne annotation, or a @OneToMany annotation.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface PrivateOwned { ... }
The @PrivateOwned annotation does not have attributes.
This example shows how to use the @PrivateOwned annotation to specify Employee field phoneNumbers.
Usage of the @PrivateOwned Annotation
@Entity public class Employee implements Serializable { ... @OneToMany(cascade=ALL, mappedBy="employee") @PrivateOwned public Collection getPhoneNumbers() { return phoneNumbers; } ... }
What You May Need to Know About Private Ownership of Objects
When the referenced object is privately owned, the referenced child object cannot exist without the parent object.
When you tell EclipseLink that a relationship is privately owned, you are specifying the following:
- If the source of a privately owned relationship is deleted, then delete the target. Note that this is equivalent of setting a cascade delete. For more information, see the following:
- Optimistic Version Locking Policies and Cascading
- Section 3.2.2 "Removal" of the JPA Specification
- Section 3.5.2 "Semantics of the Life Cycle Callback Methods for Entities" of the JPA Specification
- Section 4.10 "Bulk Update and Delete Operations" of the JPA Specification
- @OneToOne
- @ManyToOne
- @OneToMany
- If you remove the reference to a target from a source, then delete the target.
Do not configure privately owned relationships to 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.
The exception to this rule is the case when you have a many-to-many relationship in which a relation object is mapped to a relation table and is referenced through a one-to-many relationship by both the source and the target. In this case, if the one-to-many mapping is configured as privately owned, then when you delete the source, all the association objects will be deleted.
For more information, see How to Use the privateOwnedRelationship Attribute.
How to Use the @JoinFetch Annotation
You can specify the @JoinFetch annotation for the following mappings:
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface JoinFetch { ... }
Using the @JoinFetch annotation, you can enable the joining and reading of the related objects in the same query as the source object.
Note: We recommend setting join fetching at the query level, as not all queries require joining. For more information, see Using Join Reading with ObjectLevelReadQuery. |
Alternatively, you can use batch reading, especially for collection relationships. For more information, see Using Batch Reading.
This table lists attributes of the @JoinFetch annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the org.eclipse.persistence.annotations.JoinFetchType enumerated type of the fetch that you will be using.The following are the valid values for the JoinFetchType:
Note: Outer joining allows for null or empty values. For more information, see the following: |
JoinFetchType.INNER |
optional |
This example shows how to use the @JoinFetch annotation to specify Employee field managedEmployees.
Usage of the @JoinFetch Annotation
@Entity public class Employee implements Serializable { ... @OneToMany(cascade=ALL, mappedBy="owner") @JoinFetch(value=OUTER) public Collection getManagedEmployees() { return managedEmployees; } ... }
How to Use the @Mutable Annotation
You can use the @Mutable annotation on any @Basic mapping type.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Mutable { ... }
Using the @Mutable annotation, you can indicate that the value of a complex field itself can be changed or not changed (instead of being replaced).
By default, EclipseLink assumes that Serializable types are mutable. In other words, EclipseLink assumes the default @Mutable(value=true).
You can override this configuration using @Mutable(value=false).
By default, EclipseLink assumes that all @Basic mapping types, except Serializable types, are immutable.
You can override this configuration using @Mutable(value=true). For example, if you need to call Date or Calendar set methods, you can decorate a Date or Calendar persistent field using @Mutable(value=true).
Note: For Date and Calendar types only, you can configure all such persistent fields as mutable by setting global persistence unit property eclipselink.temporal.mutable to true. For more information, see the EclipseLink JPA Persistence Unit Properties for Mappings table. |
Mutable basic mappings affect the overhead of change tracking. Attribute change tracking can only be weaved with immutable mappings.
For more information, see the following:
This table lists attributes of the @Mutable annotation.
Attributes of the @Mutable Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to one of the following boolean values:
|
false |
optional |
This example shows how to use the @Mutable annotation to specify Employee field managedEmployees.
Usage of the @Mutable Annotation
@Entity public class Employee implements Serializable { ... @OneToOne(cascade=ALL, mappedBy="owner") @Mutable(value=true) public Calendar getHireDate() { return hireDate; } ... }
How to Use the Persistence Unit Properties for Mappings
This table lists the persistence unit properties that you can define in a persistence.xml file to configure EclipseLink mappings.
EclipseLink JPA Persistence Unit Properties for Mappings
Property | Usage | Default |
---|---|---|
eclipselink.temporal.mutable |
Specify whether or not EclipseLink JPA should handle all Date and Calendar persistent fields as mutable objects. The following are the valid values:
For more information, see the following:
<property name="eclipselink.temporal.mutable" value="true"/>
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.TEMPORAL_MUTABLE, "false"); |
false |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What you May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What you May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Converters
EclipseLink defines the following converter annotations (in addition to JPA-defined ones):
EclipseLink persistence provider searches the converter annotations in the following order:
- @Converter
- @Enumerated
- @Lob
- @Temporal
- Serialized (automatic)
You can define converters at the class, field and property level. You can specify EclipseLink converters on the following classes:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass;
- @Embeddable.
EclipseLink supports the use of converters with the following:
If you specify a converter with any other type of mapping annotation, EclipseLink will throw an exception.
How to Use the @Converter Annotation
You can use @Converter annotation to specify a custom converter for modification of the data value(s) during the reading and writing of a mapped attribute.
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface Converter { ... }
This table lists attributes of the @Converter annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the String name for your converter. Ensure that this name is unique across the persistence unit |
no default |
required |
converterClass |
Set this attribute to the Class of your converter. This class must implement the EclipseLink org.eclipse.persistence.mappings.converters.Converter interface. |
no default |
required |
This example shows how to use the @Converter annotation to specify Employee field gender.
Usage of 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; } ... }
How to Use the @TypeConverter Annotation
The @TypeConverter is an EclipseLink-specific annotation. You can use it to specify an EclipseLink org.eclipse.persistence.mappings.converters.TypeConversionConverter for modification of the data value(s) during the reading and writing of a mapped attribute.
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface TypeConverter { ... }
This table lists attributes of the @TypeConverter annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the String name for your converter. Ensure that this name is unique across the persistence unit |
no default |
required |
dataType |
Set this attribute to the type stored in the database. |
void.class Note: The default is inferred from the type of the persistence field or property. |
optional |
objectType |
Set the value of this attribute to the type stored on the entity. |
void.class Note: The default is inferred from the type of the persistence field or property. |
optional |
This example shows how to use the @TypeConverter annotation to convert the Double value stored in the database to a Float value stored in the entity.
Usage of the @TypeConverter Annotation
@Entity public class Employee implements Serializable{ ... @TypeConverter ( name="doubleToFloat", dataType=Double.class, objectType=Float.class, ) @Convert("doubleToFloat") public Number getGradePointAverage() { return gradePointAverage; } ... }
How to Use the @ObjectTypeConverter Annotation
You can use the @ObjectTypeConverter annotation to specify an EclipseLink 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.
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface ObjectTypeConverter { ... }
This table lists attributes of the @ObjectTypeConverter annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the String name for your converter. Ensure that this name is unique across the persistence unit |
no default |
required |
dataType |
Set this attribute to the type stored in the database. |
void.class Note: The default is inferred from the type of the persistence field or property. |
optional |
objectType |
Set the value of this attribute to the type stored on the entity. |
void.class Note: The default is inferred from the type of the persistence field or property. |
optional |
conversionValues |
Set the value of this attribute to the array of conversion values (instances of ConversionValue: String objectValue and String dataValue. See the Usage of the @ObjectTypeConverter Annotation example, to be used with the object converter. |
no default |
required |
defaultObjectValue |
Set the value of this attribute to the default object value. Note that this argument is for dealing with legacy data if the data value is missing. |
empty String |
optional |
This example shows how to use the @ObjectTypeConverter annotation to specify the Employee field gender.
Usage of 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; } ... }
How to Use the @StructConverter Annotation
The @StructConverter is an EclipseLink-specific annotation. You can add it to an org.eclipse.persistence.platform.database.DatabasePlatform using its addStructConverter method to enable custom processing of java.sql.Struct types.
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface StructConverter { ... }
This table lists attributes of the @StructConverter annotation.
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the String name for your converter. Ensure that this name is unique across the persistence unit. |
no default |
required |
converter |
Set this attribute to the converter class as a String. This class must implement the EclipseLink org.eclipse.persistence.mappings.converters.Converter interface. |
no default |
required |
This example shows how to define the @StructConverter.
Defining the @StructConverter
@StructConverter(name="MyType", converter="myproject.converters.MyStructConverter")
You can specify the @StructConverter annotation anywhere in an Entity with the scope being the whole session.
EclipseLink will throw an exception if you add more than one StructConverter that affects the same Java type.
A @StructConverter exists in the same namespaces as @Converter (see How to Use the @Converter Annotation). EclipseLink will throw a validation exception if you add a Converter and a StructConverter of the same name.
Note: You can also configure structure converters in a sessions.xml file (see What You May Need to Know About EclipseLink JPA Overriding Mechanisms). |
Using Structure Converters to Configure Mappings
In EclipseLink, a DatabasePlatform (see Database Platforms) holds a structure converter. An org.eclipse.persistence.database.platform.converters.StructConverter affects all objects of a particular type read into the Session that has that DatabasePlatform. This prevents you from configuring the StructConverter on a mapping-by-mapping basis. To configure mappings that use the StructConverter, you call their setFieldType(java.sql.Types.STRUCT) method. You must call this method on all mappings that the StructConverter will affect – if you do not call it, errors might occur.
The JPA specification requires all @Basic mappings (see @Basic) that map to a non-primitive or a non-primitive-wrapper type have a serialized converter added to them. This enables certain STRUCT types to map to a field without serialization.
You can use the existing @Convert annotation with its value attribute set to the StructConverter name – in this case, EclipseLink will apply appropriate settings to the mapping. This setting will be 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.
For more information, see the following:
How to Use the @Convert Annotation
The @Convert annotation specifies that a named converter should be used with the corresponding mapped attribute.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Convert { ... }
The @Convert has the following reserved names:
- serialized – places the org.eclipse.persistence.mappings.converters.SerializedObjectConverter on the associated mapping.
- none – does not place a converter on the associated mapping.
This table lists attributes of the @Convert annotation.
Attributes of the @Convert Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the String name for your converter. |
"none" String |
optional |
This example shows how to use the @Convert annotation to define the Employee field gender.
Usage of 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; } ... }
Using EclipseLink JPA Extensions for Entity Caching
The EclipseLink cache is an in-memory repository that stores recently read or written objects based on class and primary key values. EclipseLink uses the cache to do the following:
- Improve performance by holding recently read or written objects and accessing them in-memory to minimize database access.
- Manage locking and isolation level.
- Manage object identity.
For more information about the EclipseLink cache and its default behavior, see Introduction to Cache.
EclipseLink defines the following entity caching annotations:
EclipseLink also provides a number of persistence unit properties that you can specify to configure the EclipseLink cache (see How to Use the Persistence Unit Properties for Caching). These properties may compliment or provide an alternative to the usage of annotations. For more information, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
How to Use the @Cache Annotation
EclipseLink uses identity maps to cache objects in order to enhance performance, as well as maintain object identity. You can control the cache and its behavior by decorating your entity classes with the @Cache annotation.
@Target({TYPE}) @Retention(RUNTIME) public @interface Cache { ... }
You may define the @Cache annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass (see @MappedSuperclass);
- the root of the inheritance hierarchy (if applicable).
Note: If you define the @Cache annotation on an inheritance subclass, the annotation will be ignored. |
Attributes of the @Cache Annotation
Attribute | Description | Default | Required or Optional | Override with Persistence Unit Property |
---|---|---|---|---|
type |
Set this attribute to the type (org.eclipse.persistence.annotations.CacheType enumerated type) of the cache that you will be using. The following are the valid values for the CacheType:
|
CacheType.SOFT_WEAK |
optional |
- eclipselink.cache.type.<ENTITY>- eclipselink.cache.type.default|eclipselink.cache.type.default |
size |
Set this attribute to an int value to define the size of cache to use. |
100 | | |
isolated |
Set this attribute to a boolean value to indicate whether cached instances should be in the shared cache or in a client isolated cache (see Isolated Client Session Cache). |
false |
optional | |
expiry |
Set this attribute to the int value to enable the expiration of the cached instance after a fixed period of time (milliseconds). Queries executed against the cache after this will be forced back to the database for a refreshed copy. |
-1 (no expiry) |
optional | |
expiryTimeOfDay |
Set this attribute to a specific time of day (org.eclipse.persistence.annotations.TimeOfDay) when the cached instance will expire. Queries executed against the cache after this will be forced back to the database for a refreshed copy. |
@TimeOfDay(specified=false) |
optional | |
alwaysRefresh |
Set this attribute to a boolean value of true to force all queries that go to the database to always refresh the cache. |
false |
optional | |
refreshOnlyIfNewer |
Set this attribute to a boolean value of true to force all queries that go to the database to refresh the cache only if the data received from the database by a query is newer than the data in the cache (as determined by the optimistic locking field). Note: This option only applies if one of the other refreshing options, such as alwaysRefresh, is already enabled. Note: A version field is necessary to apply this feature. For more information, see the following:
|
false |
optional | |
disableHits |
Set this attribute to a boolean value of true to force all queries to bypass the cache for hits, but still resolve against the cache for identity. This forces all queries to hit the database. |
false |
optional | |
coordinationType |
Set this attribute to the cache coordination mode (org.eclipse.persistence.annotations.CacheCoordinationType enumerated type). The following are the valid values for the CacheCoordinationType:
|
CacheCoordinationType.SEND_OBJECT_CHANGES |
optional | |
Note: If you define the @Cache annotation on @Embeddable (see @Embeddable), EclipseLink will throw an exception. |
This example shows how to achieve the desired behavior of the EclipseLink cache by defining the attributes of the @Cache annotation.
Usage of @Cache Annotation
@Entity @Table(name="EMPLOYEE") @Cache ( type=CacheType.WEAK, isolated=false, expiry=600000, alwaysRefresh=true, disableHits=true, coordinationType=INVALIDATE_CHANGED_OBJECTS ) public class Employee implements Serializable { ... }
What You May Need to Know About Version Fields
By default, EclipseLink persistence provider assumes that the application is responsible for data consistency.
Use the @Version annotation (see Configuring Locking) to enable the JPA-managed optimistic locking by specifying the version field or property of an entity class that serves as its optimistic lock value (recommended).
When choosing a version field or property, ensure that the following is true:
- there is only one version field or property per entity;
- you choose a property or field persisted to the primary table (see Section 9.1.1 "Table Annotation" of the JPA Specification);
- your application does not modify the version property or field.
How to Use the Persistence Unit Properties for Caching
The EclipseLink JPA Properties for Caching table lists the persistence unit properties that you can define in a persistence.xml file to configure the EclipseLink cache.
For more information, see the following:
- Introduction to Cache
- What You May Need to Know About EclipseLink JPA Overriding Mechanisms
- What You May Need to Know About Overriding Annotations in JPA
- What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties
EclipseLink JPA Properties for Caching
Property | Usage | Default |
---|---|---|
eclipselink.cache.type.default |
The default type of session cache. A session cache is a shared cache that services clients attached to a given session. When you read objects from or write objects to the data source using a client session, EclipseLink saves a copy of the objects in the parent server session's cache and makes them accessible to child client sessions. From a JPA perspective, an EntityManagerFactory wraps an org.eclipse.persistence.sessions.server.ServerSession; entity managers wrap an org.eclipse.persistence.sessions.UnitOfWork and org.eclipse.persistence.sessions.server.ClientSession. For more information about sessions, see Introduction to EclipseLink Sessions. The following are the valid values for the org.eclipse.persistence.jpa.config.CacheType:
Note: The values are case-sensitive. Note: Using this property, you can override the @Cache annotation (see How to Use the @Cache Annotation) attribute type.
<property name="eclipselink.cache.type.default" value="Full"/> Example: property Map import org.eclipse.persistence.jpa.config.CacheType; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_TYPE_DEFAULT, CacheType.Full); |
CacheType.SoftWeak |
eclipselink.cache.size.default |
The default maximum number of objects allowed in an EclipseLink cache. Valid values: 0 to Integer.MAX_VALUE as a String.
<property name="eclipselink.cache.size.default" value="5000"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SIZE_DEFAULT, 5000); |
1000 |
eclipselink.cache.shared.default |
The default for whether or not the EclipseLink session cache is shared by multiple client sessions. The following are the valid values:
<property name="eclipselink.cache.shared.default" value="true"/>
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, "true"); |
true |
eclipselink.cache.type.<ENTITY> |
The type of session cache for the JPA entity named <ENTITY> or with the class name <ENTITY>. The following are the valid values for the org.eclipse.persistence.jpa.config.CacheType:
<property name="eclipselink.cache.type.Order" value="Full"/> Example: property Map import org.eclipse.persistence.jpa.config.CacheType; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_TYPE+".Order", CacheType.Full); |
eclipselink.cache.type.default |
eclipselink.cache.size.<ENTITY> |
The maximum number of JPA entities of the type denoted by JPA entity name <ENTITY> allowed in an EclipseLink cache. For more information on entity names, see Section 8.1 "Entity" of the JPA Specification. Valid values: 0 to Integer.MAX_VALUE as a String.
<property name="eclipselink.cache.size.Order" value="5000"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SIZE+".Order", 1000); |
eclipselink.cache.size.default |
eclipselink.cache.shared.<ENTITY> |
Whether or not the EclipseLink session cache is shared by multiple client sessions for JPA entities of the type denoted by JPA entity name <ENTITY>. The following are the valid values:
<property name="eclipselink.cache.shared.Order" value="true"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SHARED+".Order", "true"); |
eclipselink.cache.shared.default |
How to Use the @TimeOfDay Annotation
You can use the @TimeOfDay annotation to specify a time of day using a Calendar instance. By doing so, you configure cache expiry on an entity class.
@Target({}) @Retention(RUNTIME) public @interface TimeOfDay { ... }
This table lists attributes of the @TimeOfDay annotation.
Attributes of the @TimeOfDay Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
hour |
Set this attribute to the int value representing an hour of the day. |
0 |
optional |
minute |
Set this attribute to the int value representing a minute of the day. |
0 |
optional |
second |
Set this attribute to the int value representing a second of the day. |
0 |
optional |
millisecond |
Set this attribute to the int value representing a millisecond of the day. |
0 |
optional |
Using EclipseLink JPA Extensions for Customization and Optimization
EclipseLink defines one descriptor customizer annotation – @Customizer (see How to Use the @Customizer Annotation).
EclipseLink also provides a number of persistence unit properties that you can specify to configure EclipseLink customization and validation (see How to Use the Persistence Unit Properties for Customization and Validation). These properties may compliment or provide an alternative to the usage of annotations.
Note: Persistence unit properties always override the corresponding annotations' attributes. For more information, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties. |
In addition, EclipseLink provides a persistence unit property that you can specify to optimize your application (see How to Use the Persistence Unit Properties for Optimization).
How to Use the @Customizer Annotation
Use the @Customizer annotation to specify a class that implements the org.eclipse.persistence.tools.sessionconfiguration.DescriptorCustomizer interface and that is to be run against a class' descriptor after all metadata processing has been completed. See eclipselink.descriptor.customizer.<ENTITY> for more information.
@Target({TYPE}) @Retention(RUNTIME) public @interface Customizer { ... }
You can define the @Customizer annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass)
- @Embeddable)
Note: A @Customizer is not inherited from its parent classes. |
This table lists attributes of the @Customizer annotation.
Attributes of the @Customizer Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the Class of the descriptor customizer that you want to apply to your entity's descriptor. |
no default |
required |
This example shows how to use the @Customizer annotation.
Usage of the @Customizer Annotation
@Entity @Table(name="EMPLOYEE") @Customizer(mypackage.MyCustomizer.class) public class Employee implements Serializable { ... }
How to Use the Persistence Unit Properties for Customization and Validation
This table lists the persistence unit properties that you can define in a persistence.xml file to configure EclipseLink customization and validation.
EclipseLink JPA Properties for Customization and Validation
Property | Usage | Default |
---|---|---|
eclipselink.orm.throw.exceptions |
Specify whether or not EclipseLink JPA should throw an exception or log a warning when it encounters a problem with any of the files listed in a persistence.xml file <mapping-file> element. The following are the valid values:
<property name="oracle.orm.throw.exceptions" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.ECLIPSELINK_ORM_THROW_EXCEPTIONS, "false"); |
true |
persistence.tools.weaving |
Control whether or not the weaving of the entity classes is performed. The EclipseLink JPA persistence provider uses weaving to enhance JPA entities for such things as lazy loading, change tracking, fetch groups, and internal optimizations. The following are the valid values:
Use this option if you plan to execute your application outside of a Java EE 5 container in an environment that does not permit the use of -javaagent:eclipselink-agent.jar on the JVM command line. For more information, see the following:
<property name="persistence.tools.weaving" value="false"/>
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING, "false"); |
true |
persistence.tools.weaving.lazy |
Enable or disable the lazy one-to-one (see @OneToOne) mapping through weaving. The following are the valid values:
Note: you may set this option only if the persistence.tools.weaving option is set to true. The purpose of the persistence.tools.weaving.lazy option is to provide more granular control over weaving. For more information, see the following:
<property name="persistence.tools.weaving.lazy" value="false"/>
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_LAZY, "false"); |
true |
persistence.tools.weaving.changetracking |
Enable or disable the AttributeLevelChangeTracking through weaving. The following are the valid values:
Note: you may set this option only if the persistence.tools.weaving option is set to true. The purpose of the persistence.tools.weaving.changetracking option is to provide more granular control over weaving. For more information, see the following:
<property name="persistence.tools.weaving.changetracking" value="false"/>
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "false"); |
true |
persistence.tools.weaving.fetchgroups |
Enable or disable fetch groups through weaving. The following are the valid values:
Note: you may set this option only if the persistence.tools.weaving option is set to true. The purpose of the persistence.tools.weaving.fetchgroups option is to provide more granular control over weaving. For more information, see the following:
<property name="persistence.tools.weaving.fetchgroups" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_FETCHGROUPS, "false"); |
true |
eclipselink.session.customizer |
Specify an EclipseLink session customizer class: a Java class that implements the org.eclipse.persistence.tools.sessionconfiguration.SessionCustomizer interface and provides a default (zero-argument) constructor. Use this class' customize method, which takes an org.eclipse.persistence.sessions.Session, to programmatically access advanced EclipseLink session API. For more information, see Session Customization. Valid values: class name of a SessionCustomizer class fully qualified by its package name.
<property name="eclipselink.session.customizer" value="acme.sessions.MySessionCustomizer"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, "acme.sessions.MySessionCustomizer"); | |
eclipselink.descriptor.customizer.<ENTITY> |
Specify an EclipseLink descriptor customizer class – a Java class that implements the org.eclipse.persistence.tools.sessionconfiguration.DescriptorCustomizer interface and provides a default (zero-argument) constructor. Use this class's customize method, which takes an org.eclipse.persistence.descriptors.ClassDescriptor, to programmatically access advanced EclipseLink descriptor and mapping API for the descriptor associated with the JPA entity named <ENTITY>. For more information on entity names, see Section 8.1 "Entity" of the JPA Specification For more information, see Descriptor Customization. Note: EclipseLink does not support multiple descriptor customizers.Valid values: class name of a DescriptorCustomizer class fully qualified by its package name.
<property name="eclipselink.descriptor.customizer.Order" value="acme.sessions.MyDescriptorCustomizer"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER+".Order", "acme.sessions.MyDescriptorCustomizer"); | |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA ]and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
How to Use the Persistence Unit Properties for Optimization
This table lists the persistence unit properties that you can define in a persistence.xml file to optimize your EclipseLink application.
EclipseLink JPA Persistence Unit Properties for Optimization
Property | Usage | Default |
---|---|---|
eclipselink.profiler |
The type of the performance profiler. For more information on performance profilers, see Optimizing the EclipseLink Application. The following are the valid values for the org.eclipse.persistence.jpa.config.ProfilerType:
<property name="eclipselink.profiler" value="PerformanceProfiler"/> Example: property Map import org.eclipse.persistence.jpa.config.ProfilerType; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.PROFILER, ProfilerType.PerformanceProfiler); Example: persistence.xml file <property name="eclipselink.profiler" value="mypackage.com.MyProfiler"/> Note: Ensure that MyProfiler is in your classpath. Example: property Map import org.eclipse.persistence.jpa.config.ProfilerType; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.PROFILER, "mypackage.com.MyProfiler"); |
ProfilerType.NoProfiler |
For information about optimization, see Optimizing the EclipseLink Application
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Extensions for Declaration of Read-Only Classes
EclipseLink defines one annotation that you can use to declare classes as read-only – @ReadOnly (see How to Use the @ReadOnly Annotation).
For more information, see the following:
How to Use the @ReadOnly Annotation
Use the @ReadOnly annotation to specify that a class is read-only (see Declaring Read-Only Classes).
Note: Any changes made within a managed instance in a transaction or to a detached instance and merged will have no effect in the context of a read-only entity class. |
@Target({TYPE}) @Retention(RUNTIME) public @interface ReadOnly { ... }
You can define the @ReadOnly annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass (see @MappedSuperclass);
- the root of the inheritance hierarchy (if applicable).
The @ReadOnly annotation does not have attributes.
This example shows how to use the @ReadOnly annotation.
Usage of the @ReadOnly Annotation
@Entity @ReadOnly public class Employee implements Serializable { ... }
Using EclipseLink JPA Extensions for Returning Policy
The returning policy enables INSERT or UPDATE operations to return values back into the object being written. These values include table default values, trigger or stored procedures computed values. For more information, see Configuring Returning Policy.
EclipseLink defines the following returning policy annotations:
- @ReturnInsert (see How to Use the @ReturnInsert Annotation)
- @ReturnUpdate (see How to Use the @ReturnInsert Annotation)
How to Use the @ReturnInsert Annotation
You can only specify the @ReturnInsert for a @Basic mapping (see @Basic).
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface ReturnInsert { ... }
This table lists attributes of the @ReturnInsert annotation.
Attributes of the @ReturnInsert Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
returnOnly |
Set this attribute to the boolean value of true if you want a return of a value for this field, without including the field in the insert. |
false |
optional |
The Usage of the @ReturnInsert Annotation Without Arguments example shows how to use the @ReturnInsert annotation without specifying the value for the returnOnly argument, therefore accepting the default value of false. The Usage of the @ReturnInsert Annotation with Arguments example shows how to set the value of the returnOnly argument to true.
Usage of the @ReturnInsert Annotation Without Arguments
@ReturnInsert public String getFirstName() { return firstName; }
Usage of the @ReturnInsert Annotation with Arguments
@ReturnInsert(returnOnly=true) public String getFirstName() { return firstName; }
How to Use the @ReturnUpdate Annotation
You can only specify the @ReturnUpdate for a @Basic mapping (see @Basic).
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface ReturnUpdate { ... }
The @ReturnUpdate annotation does not have attributes.
This example shows how to use the @ReturnUpdate annotation.
Usage of the @ReturnUpdate Annotation
@ReturnUpdate public String getFirstName() { return firstName; }
Using EclipseLink JPA Extensions for Optimistic Locking
EclipseLink defines one annotation for optimistic locking – @OptimisticLocking (see How to Use the @OptimisticLocking Annotation).
For more information, see the following:
How to Use the @OptimisticLocking Annotation
You can use the @OptimisticLocking annotation to specify the type of optimistic locking that EclipseLink should use when updating or deleting entities.
Note: EclipseLink supports additional optimistic locking policies beyond what is supported through the JPA specification (such as @Version - see Section 9.1.17 "Version Annotation" of the JPA Specification). When mapping to a database schema where a version column does not exist and cannot be added, these locking policies enable the concurrency protection. |
@Target({TYPE}) @Retention(RUNTIME) public @interface OptimisticLocking { ... }
This table lists attributes of the @OptimisticLocking annotation.
Attributes of the @OptimisticLocking Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
type |
Set this attribute to the type (org.eclipse.persistence.annotations.OptimisticLockingType enumerated type) of the optimistic locking policy that you will be using. The following are the valid values for the OptimisticLockingType:
|
OptimisticLockingType.VERSION_COLUMN |
optional |
selectedColumns |
Set this attribute to an array of javax.persistence.Column instances. For an optimistic locking policy of type SELECTED_COLUMNS, this annotation member becomes a required field. Note: EclipseLink will throw an exception if you set the SELECTED_COLUMNS type, but fail to specify the selectedColumns. You must also specify the name attribute of Column. |
empty Column array |
optional |
cascade |
Set the value of this attribute to a boolean value of true to specify that the optimistic locking policy should cascade the lock. By enabling cascading you configure EclipseLink to automatically force a version field update on a parent object when its privately owned child object's version field changes. Note: In the current release, only supported with VERSION_COLUMN locking. For more information, see the following: |
false |
optional |
Note: Setting an @OptimisticLocking may override any @Version specification (see Section 9.1.17 "Version Annotation" of the JPA Specification) on the entity: EclipseLink will not throw an exception, but will log a warning. You can specify @Version without any @OptimisticLocking specification to define a version locking policy (org.eclipse.persistence.descriptors.VersionLockingPolicy) on the source entity. |
This example shows how to use the @OptimisticLocking annotation with the ALL_COLUMNS type.
Usage of the @OptimisticLocking Annotation - ALL_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=OptimisticLockingType.ALL_COLUMNS) public class Employee implements Serializable{ private Integer id; private String firstName; private String lastName; ... }
The following example shows how to use the @OptimisticLocking annotation with the CHANGED_COLUMNS type.
Usage of the @OptimisticLocking Annotation - CHANGED_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=OptimisticLockingType.CHANGED_COLUMNS) public class Employee implements Serializable{ private Integer id; private String firstName; private String lastName; ... }
The following example shows how to use the @OptimisticLocking annotation with the SELECTED_COLUMNS type.
Usage of the @OptimisticLocking Annotation - SELECTED_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking( type=OptimisticLockingType.SELECTED_COLUMNS, selectedColumns={@Column(name="id"), @Column(name="lastName")} ) public class Employee implements Serializable{ @Id private Integer id; private String lastName; private String lastName; ... }
The following example shows how to use the @OptimisticLocking annotation with the VERSION_COLUMN type.
Usage of the @OptimisticLocking Annotation - VERSION_COLUMN
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=OptimisticLockingType.VERSION_COLUMN, cascade=true) public class Employee implements Serializable{ private String firstName; private String lastName; @Version private int version; ... }
Using EclipseLink JPA Extensions for Stored Procedure Query
EclipseLink defines the following stored procedure query annotations:
- @NamedStoredProcedureQuery (see How to Use the @NamedStoredProcedureQuery Annotation);
- @NamedStoredProcedureQueries (see How to Use the @NamedStoredProcedureQueries Annotation).
You can execute a stored procedure query like any other named query (see Named Queries). For more information, see Queries.
How to Use the @NamedStoredProcedureQuery Annotation
Use the @NamedStoredProcedureQuery to define queries that call stored procedures as named queries.
@Target({TYPE}) @Retention(RUNTIME) public @interface NamedStoredProcedureQuery { ... }
This table lists attributes of the @NamedStoredProcedureQuery annotation.
Attributes of the @NamedStoredProcedureQuery Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
name |
Set this attribute to the unique String name that references this stored procedure query. |
no default |
required |
hints |
Set this attribute to an array of javax.persistence.QueryHint instances. |
empty QueryHint array |
optional |
resultClass |
Set this attribute to the Class of the query result. |
void.class |
optional |
resultSetMapping |
Set this attribute to the String name of the javax.persistence.SQLResultSetMapping instance. |
empty String |
optional |
procedureName |
Set this attribute to the String name of the stored procedure. |
no default |
required |
returnsResultSet |
Set this attribute to the boolean value of false to disable the return of the result set. |
true |
optional |
procedureParameters |
Set the value of this attribute to an array of org.eclipse.persistence.annotations.StoredProcedureParameter instances to define arguments to the stored procedure. The following are attributes of the StoredProcedureParameter:
For more information, see the following: |
empty StoredProcedureParameter array |
optional |
This example shows how to use the @NamedStoredProcedureQuery annotation.
Usage of the @NamedStoredProcedureQuery Annotation
@Entity @Table(name="EMPLOYEE") @NamedStoredProcedureQuery( name="ReadEmployee", procedureName="Read_Employee", storedProcedureParameters={ @StoredProcedureParameter(queryParamater="EMP_ID")} ) public class Employee implements Serializable{ ... }
How to Use the @NamedStoredProcedureQueries Annotation
Use the @NamedStoredProcedureQueries to define queries that call stored procedures as named queries.
@Target({TYPE}) @Retention(RUNTIME) public @interface NamedStoredProcedureQueries { ... }
This table lists attributes of the @NamedStoredProcedureQueries annotation.
Attributes of the @NamedStoredProcedureQueries Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the array of @NamedStoredProcedureQuery (see How to Use the @NamedStoredProcedureQuery Annotation). |
no default |
required |
Using EclipseLink JPA Extensions for JDBC
EclipseLink JPA provides persistence unit properties that you can define in a persistence.xml file to configure how EclipseLink will use the connections returned from the data source used. These properties are divided into the two following categories:
- Options that you can use to configure how EclipseLink communicates with the JDBC connection (see How to Use EclipseLink JPA Extensions for JDBC Connection Communication).
- Options that you can use to configure EclipseLink own connection pooling (see How to Use EclipseLink JPA Extensions for JDBC Connection Pooling).
How to Use EclipseLink JPA Extensions for JDBC Connection Communication
This table lists the EclipseLink JPA persistence unit properties that you can define in a persistence.xml file to configure how EclipseLink communicates with the JDBC connection.
EclipseLink JPA Persistence Unit Properties for JDBC Connection Communication
Property | Usage | Default |
---|---|---|
eclipselink.jdbc.bind-parameters |
Control whether or not the query uses parameter binding. Note: this property applies when used in a Java SE environment. For more information, see How to Use Parameterized SQL (Parameter Binding) and Prepared Statement Caching for Optimization. The following are the valid values:
<property name="eclipselink.jdbc.bind-parameters" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_BIND_PARAMETERS, "false"); |
true |
eclipselink.jdbc.native-sql |
Enable or disable EclipseLink's generation of database platform-specific SQL (as opposed to generic SQL). Note: this property applies when used both in a Java SE and Java EE environment. The following are the valid values:
<property name="eclipselink.jdbc.native-sql" value="true"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.NATIVE_SQL, "true"); |
false |
eclipselink.jdbc.batch-writing |
Specify the use of batch writing to optimize transactions with multiple write operations. Set the value of this property into the session at deployment time. Note: this property applies when used both in a Java SE and Java EE environment. The following are the valid values for org.eclipse.persistence.jpa.config.BatchWriting:
Note: if you set any other value, EclipseLink will throw an exception.
<property name="eclipselink.jdbc.batch-writing" value="Oracle-JDBC"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.OracleJDBC); |
None |
eclipselink.jdbc.cache-statements |
Enable or disable EclipseLink internal statement caching. Note: we recommend enabling this functionality if you are using EclipseLink connection pooling. Note: this property applies when used both in a Java SE and Java EE environment. The following are the valid values:
<property name="eclipselink.jdbc.cache-statements" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_STATEMENTS, "false"); |
false |
eclipselink.jdbc.cache-statements.size |
The number of statements held when using internal statement caching. Set the value at the deployment time. Note: this property applies when used both in a Java SE and Java EE environment. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
<property name="eclipselink.jdbc.cache-statements.size" value="2"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, "2"); |
50 |
eclipselink.jdbc.driver |
The class name of the JDBC driver you want to use, fully qualified by its package name. This class must be on your application classpath. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA Specification).
<property name="eclipselink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver"); | |
eclipselink.jdbc.password |
The password for your JDBC user. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA Specification).
<property name="eclipselink.jdbc.password" value="tiger"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_PASSWORD, "tiger"); | |
eclipselink.jdbc.url |
The JDBC connection URL required by your JDBC driver. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA Specification)
<property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@MYHOST:1521:MYSID"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_URL, "jdbc:oracle:thin:@MYHOST:1521:MYSID"); | |
eclipselink.jdbc.user |
The user name for your JDBC user. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA Specification)
<property name="eclipselink.jdbc.url" value="scott"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_USER, "scott"); | |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
How to Use EclipseLink JPA Extensions for JDBC Connection Pooling
This table lists the EclipseLink JPA persistence unit properties that you can define in a persistence.xml file to configure EclipseLink internal connection pooling (see Internal Connection Pools).
EclipseLink JPA Persistence Unit Properties for JDBC Connection Pooling
Property | Usage | Default |
---|---|---|
eclipselink.jdbc.read-connections.max |
The maximum number of connections allowed in the JDBC read connection pool. Note: This property applies when used in a Java SE environment. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
<property name="eclipselink.jdbc.read-connections.max" value="3"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX, "3"); |
2 |
eclipselink.jdbc.read-connections.min |
The minimum number of connections allowed in the JDBC read connection pool. Note: This property applies when used in a Java SE environment. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
<property name="eclipselink.jdbc.read-connections.min" value="1"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, "1"); |
2 |
eclipselink.jdbc.read-connections.shared |
Specify whether or not to allow concurrent use of shared read connections. Note: This property applies when used in a Java SE environment. The following are the valid values:
<property name="eclipselink.jdbc.read-connections.shared" value="true"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED, "true"); |
false |
eclipselink.jdbc.write-connections.max |
The maximum number of connections allowed in the JDBC write connection pool. Note: This property applies when used in a Java SE environment. Valid values: to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
<property name="eclipselink.jdbc.write-connections.max" value="5"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX, "5"); |
10 |
eclipselink.jdbc.write-connections.min |
The maximum number of connections allowed in the JDBC write connection pool. Note: This property applies when used in a Java SE environment. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
<property name="eclipselink.jdbc.write-connections.min" value="2"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN, "2"); |
5 |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPAand What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see hat You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Extensions for Logging
This table lists the EclipseLink JPA persistence unit properties that you can define in a persistence.xml file to configure EclipseLink logging (see Logging).
EclipseLink JPA Persistence Unit Properties for Logging
Property | Usage | Default |
---|---|---|
eclipselink.logging.logger |
Select the type of logger to use. The following are the valid values:
<property name="eclipselink.logging.logger" value="acme.loggers.MyCustomLogger" /> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_LOGGER, "acme.loggers.MyCustomLogger" /> |
DefaultLogger |
eclipselink.logging.level |
Control the amount and detail of log output by configuring the log level (in ascending order of information). The following are the valid values for the java.util.logging.Level:
<property name="eclipselink.logging.level" value="INFO"/> Example: property Map import java.util.logging.Level; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_LEVEL, Level.INFO); |
Level.INFO |
eclipselink.logging.timestamp |
Control whether the timestamp is logged in each log entry. The following are the valid values:
<property name="eclipselink.logging.timestamp" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_TIMESTAMP, "false"); |
true |
eclipselink.logging.thread |
Control whether a thread identifier is logged in each log entry.The following are the valid values:
Example: persistence.xml file <property name="eclipselink.logging.thread" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_THREAD, "false"); |
true |
eclipselink.logging.session |
Control whether an EclipseLink session identifier is logged in each log entry.The following are the valid values:
Example: persistence.xml file <property name="eclipselink.logging.session" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_SESSION, "false"); |
true |
eclipselink.logging.exceptions |
Control whether the exceptions thrown from within the EclipseLink code are logged prior to returning the exception to the calling application. Ensures that all exceptions are logged and not masked by the application code. The following are the valid values:
<property name="eclipselink.logging.exceptions" value="true"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_EXCEPTIONS, "true"); |
false |
eclipselink.logging.file |
Specify a file location for the log output (instead of the standard out). Note: This property applies when used in a Java SE environment. Valid values: a string location to a directory in which you have write access. The location may be relative to your current working directory or absolute.
<property name="eclipselink.logging.file" value="C:\myout\"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_FILE, "C:\myout\"); | |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Extensions for Session, Target Database and Target Application Server
This table lists the EclipseLink JPA persistence unit properties that you can define in a persistence.xml file to configure EclipseLink extensions for session, as well as the target database and application server.
EclipseLink JPA Persistence Unit Properties for Database, Session, and Application Server
Property | Usage | Default |
---|---|---|
eclipselink.session-name |
Specify the name by which the EclipseLink session is stored in the static session manager. Use this option if you need to access the EclipseLink shared session outside of the context of the JPA or to use a pre-existing EclipseLink session configured through an EclipseLink sessions.xml file. Valid values: a valid EclipseLink session name that is unique in a server deployment.
<property name="eclipselink.session-name" value="MySession"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.SESSION_NAME, "MySession"); |
EclipseLink-generated unique name. |
eclipselink.sessions-xml |
Specify persistence information loaded from the EclipseLink session configuration file (sessions.xml). You can use this option as an alternative to annotations and deployment XML. If you specify this property, EclipseLink will override all class annotation and the object relational mapping from the persistence.xml, as well as ORM.xml and other mapping files, if present. For more information, see hat You May Need to Know About EclipseLink JPA Overriding Mechanisms. Indicate the session by setting the eclipselink.session-name property. Note: If you do not specify the value for this property, sessions.xml file will not be used. Valid values: the resource name of the sessions XML file.
<property name="eclipselink.sessions-xml" value="mysession.xml"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.SESSIONS_XML, "mysession.xml"); | |
eclipselink.session-event-listener |
Specify a descriptor event listener to be added during bootstrapping. For more information, see Obtaining an Entity Manager Factory in Java SE Environment. Valid values: qualified class name for a class that implements the org.eclipse.persistence.sessions.SessionEventListener interface.
<property name="eclipselink.session-event-listener" value="mypackage.MyClass.class"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, "mypackage.MyClass.class"); | |
eclipselink.session.include.descriptor.queries |
Enable or disable the default copying of all named queries (see Named Queries) from the descriptors to the session. These queries include the ones defined using EclipseLink API, descriptor amendment methods (see Amendment and After-Load Methods), and so on. The following are the valid values:
<property name="eclipselink.session.include.descriptor.queries" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, "false"); |
true |
eclipselink.target-database |
Specify the type of database that your JPA application uses. The org.eclipse.persistence.jpa.config.TargetDatabase enumerated type contains an entry for many of the more common database types supported. The following are the valid values for the org.eclipse.persistence.jpa.config.TargetDatabase:
You can also set the value to the fully qualified classname of a subclass of the org.eclipse.persistence.platform.DatabasePlatform class.
<property name="eclipselink.target-database" value="Oracle"/> Example: property Map import org.eclipse.persistence.jpa.config.TargetDatabase; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.TARGET_DATABASE, TargetDatabase.Oracle); |
TargetDatabase.Auto |
eclipselink.target-server |
Specify the type of application server that your JPA application uses. The following are the valid values for the org.eclipse.persistence.jpa.config.TargetServer:
<property name="eclipselink.target-server" value="OC4J_10_1_3"/> Example: property Map import org.eclipse.persistence.jpa.config.TargetServer; import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.TARGET_SERVER, TargetServer.OC4J_10_1_3); |
None |
For information about the configuration of platforms, see the following:
- Target Platforms
- Integrating EclipseLink with an Application Server
- Projects and Platforms
- Database Platforms
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Extensions for Schema Generation
This table lists the EclipseLink JPA persistence unit properties that you can define in a persistence.xml file to configure schema generation.
EclipseLink JPA Persistence Unit Properties for Schema Generation
Property | Usage | Default |
---|---|---|
eclipselink.ddl-generation |
Specify what Data Definition Language (DDL) generation action you want for your JPA entities. To specify the DDL generation target, see eclipselink.ddl-generation.output-mode. The following are the valid values for the org.eclipse.persistence.jpa.config.PersistenceUnitProperties:
<property name="eclipselink.ddl-generation" value="create-tables"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY); |
none |
eclipselink.application-location |
Specify where EclipseLink should write generated DDL files (see eclipselink.create-ddl-jdbc-file-name and eclipselink.drop-ddl-jdbc-file-name). Files are written if eclipselink.ddl-generation is set to anything other than none. Valid values: a file specification to a directory in which you have write access. The file specification may be relative to your current working directory or absolute. If it does not end in a file separator, EclipseLink will append one valid for your operating system.
<property name="eclipselink.application-location" value="C:\ddl\"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.APP_LOCATION, "C:\ddl\"); |
"."+File.separator |
eclipselink.create-ddl-jdbc-file-name |
Specify the file name of the DDL file that EclipseLink generates containing SQL statements to create tables for JPA entities. This file is written to the location specified by eclipselink.application-location when eclipselink.ddl-generation is set to create-tables or drop-and-create-tables. Valid values: a file name valid for your operating system. Optionally, you may prefix the file name with a file path as long as the concatenation of eclipselink.application-location + eclipselink.create-ddl-jdbc-file-name is a valid file specification for your operating system.
<property name="eclipselink.create-ddl-jdbc-file-name" value="create.sql"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql"); |
createDDL.jdbc |
eclipselink.drop-ddl-jdbc-file-name |
Specify the file name of the DDL file that EclipseLink generates containing the SQL statements to drop tables for JPA entities. This file is written to the location specified by eclipselink.application-location when eclipselink.ddl-generation is set to drop-and-create-tables. Valid values: a file name valid for your operating system. Optionally, you may prefix the file name with a file path as long as the concatenation of eclipselink.application-location + eclipselink.drop-ddl-jdbc-file-name is a valid file specification for your operating system.
<property name="eclipselink.drop-ddl-jdbc-file-name" value="drop.sql"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql"); |
dropDDL.jdbc |
eclipselink.ddl-generation.output-mode |
Use this property to specify the DDL generation target. The following are the valid values for the org.eclipse.persistence.jpa.config.PersistenceUnitProperties:
<property name="eclipselink.ddl-generation.output-mode" value="database"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION); |
Container or Java EE mode: PersistenceUnitProperties.sql-scriptNote: This setting may be overridden by containers with specific EclipseLink support. Please, refer to your container documentation for details.Bootstrap or Java SE mode: PersistenceUnitProperties.both |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Using EclipseLink JPA Extensions for Tracking Changes
Within a transaction, EclipseLink automatically tracks entity changes.
EclipseLink defines one annotation for tracking changes – @ChangeTracking (see How to Use the @ChangeTracking Annotation).
EclipseLink also provides a number of persistence unit properties that you can specify to configure EclipseLink change tracking (see How to Use the Persistence Unit Properties for Change Tracking). These properties may compliment or provide an alternative to the usage of annotations.
Note: Persistence unit properties always override the corresponding annotations' attributes. For more information, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties. |
For more information, see Unit of Work and Change Policy.
How to Use the @ChangeTracking Annotation
Use the @ChangeTracking annotation to set the unit of work's change policy.
@Target({TYPE}) @Retention(RUNTIME) public @interface ChangeTracking { ... }
Note: This is an optimization feature that lets you tune the way EclipseLink detects changes. You should choose the strategy based on the usage and data modification patterns of the entity type as different types may have different access patterns and hence different settings, and so on. For more information, see the following: |
This table lists attributes of the @ChangeTracking annotation.
Attributes of the @ChangeTracking Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the type of the change tracking (org.eclipse.persistence.annotations.ChangeTrackingType enumerated type) to use.
Note: For every option, objects with changed attributes will be processed at the commit time to include any changes in the results of the commit. Unchanged objects will be ignored. Note: The weaving of change tracking is the same for attribute and object change tracking. For information about the relationship between the value attribute and persistence.tools.weaving.changetracking property, see What You May Need to Know About the Relationship Between the Change Tracking Annotation and Persistence Unit Property |
ChangeTrackingType.AUTO |
optional |
This example shows how to use the @ChangeTracking annotation.
Usage of @ChangeTracking Annotation
@Entity @Table(name="EMPLOYEE") @ChangeTracking(OBJECT) ( public class Employee implements Serializable { ... }
Note: You cannot use the attribute change tracking in conjunction with the following:
The attribute change tracking will not detect object changes made through reflection or direct field access to fields mapped as properties. |
How to Use the Persistence Unit Properties for Change Tracking
This table lists the persistence unit properties that you can define in a persistence.xml file to configure EclipseLink change tracking.
EclipseLink JPA Persistence Unit Properties for Change Tracking
Property | Usage | Default |
---|---|---|
persistence.tools.weaving.changetracking |
Enable or disable the AttributeLevelChangeTracking through weaving. The following are the valid values:
Note: You may set this option only if the persistence.tools.weaving option is set to true. The purpose of the persistence.tools.weaving.changetracking option is to provide more granular control over weaving. For more information, see the following:
<property name="persistence.tools.weaving.changetracking" value="false"/> Example: property Map import org.eclipse.persistence.jpa.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "false"); |
true |
For information about the relationship between the value attribute of the @ChangeTracking annotation (see How to Use the @ChangeTracking Annotation) and persistence.tools.weaving.changetracking property, see What You May Need to Know About the Relationship Between the Change Tracking Annotation and Persistence Unit Property.
For information about the use of annotations as opposed to persistence unit properties and vice versa, see What You May Need to Know About Overriding Annotations in JPA and What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
For more information about persistence unit properties, see What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties.
Change Tracking Annotation and Persistence Unit Property
What You May Need to Know About the Relationship Between the Change Tracking Annotation and Persistence Unit Property
This table shows the dependency between the value attribute of the @ChangeTracking annotation (see How to Use the @ChangeTracking Annotation) and the persistence.tools.weaving.changetracking property (see How to Use the Persistence Unit Properties for Change Tracking).
Relationship Between the Change Tracking Annotation and Property
@ChangeTracking(value=) | persistence.tools.weaving.changetracking= | Description |
---|---|---|
ATTRIBUTE |
true |
Weave and enable attribute change tracking. Even if the descriptors contain mappings that are not directly supported by change tracking weaving, EclipseLink assumes that you will either use your set methods to ensure that your changes are captured, or raise the events for these mappings. |
ATTRIBUTE |
false |
Do not weave change tracking. You must implement the org.eclipse.persistence.annotations.ChangeTracking interface and raise the change events. Otherwise, an error will occur on descriptor initialization. |
OBJECT |
true |
Object change tracking is used and change tracking is woven. Note: Weaving is identical for object and attribute change tracking. |
OBJECT |
false |
Do not weave change tracking. You must implement the org.eclipse.persistence.annotations.ChangeTracking interface and raise the change events. Otherwise, an error will occur on descriptor initialization. |
DEFERRED |
true |
Do not weave change cracking. Deferred change cracking is used. |
DEFERRED |
false |
Do not weave change cracking. Deferred change cracking is used. |
AUTO |
true |
Weave change tracking if the descriptor does not use any mappings that do not support change tracking. |
AUTO |
false |
Do not weave change cracking. Deferred change cracking is used. |
Using EclipseLink JPA Query Customization Extensions
This section describes the following:
How to Use EclipseLink JPA Query Hints
The EclipseLink JPA Query Hints table lists the EclipseLink JPA query hints that you can specify when you construct a JPA query, as the Specifying an EclipseLink JPA Query Hint example shows, or when you specify a JPA query using the @QueryHint annotation (see Section 8.3.1 "NamedQuery Annotation" of the JPA Specification), as the Specifying an EclipseLink JPA Query Hint with @QueryHint example shows.
When you set a hint, you can set the value using the public static final field in the appropriate configuration class in org.eclipse.persistence.jpa.config package, including the following:
- CacheUsage
- PessimisticLock
- EclipseLinkQueryHints
- HintValues
- QueryType
The Specifying an EclipseLink JPA Query Hint and Specifying an EclipseLink JPA Query Hint with @QueryHint examples show how to set the value of hint eclipselink.jdbc.bind-parameters using the EclipseLinkQueryHints configuration class to set the name of the hint, and the HintValues configuration class to set the value.
Specifying an EclipseLink JPA Query Hint
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; Customer customer = (Customer)entityMgr.createNamedQuery("findCustomerBySSN"). setParameter("SSN", "123-12-1234"). setHint(EclipseLinkQueryHints.BIND_PARAMETERS, HintValues.PERSISTENCE_UNIT_DEFAULT). getSingleResult();
Specifying an EclipseLink JPA Query Hint with @QueryHint
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @Entity @NamedQuery( name="findEmployeeByDept", query="SELECT e FROM Employee e WHERE e.dept=:deptNum" hints={@QueryHint= {name=EclipseLinkQueryHints.BIND_PARAMETERS, value=HintValues.TRUE} } ) public class Employee implements Serializable { ... }
EclipseLink JPA Query Hints
Hint | Usage | Default |
---|---|---|
eclipselink.cache-usage |
Specify how the query should interact with the EclipseLink cache. EclipseLink JPA uses a shared cache mechanism that is scoped to the entire persistence unit. When operations are completed in a particular persistence context, the results are merged back into the shared cache so that other persistence contexts can use them. This happens regardless of whether the entity manager and persistence context are created in Java SE or Java EE. Any entity persisted or removed using the entity manager will always be kept consistent with the cache. For more information, see the following: The following are the valid values for the org.eclipse.persistence.jpa.config.CacheUsage:
For more information, see Configuring Cache Usage for In-Memory Queries.
import org.eclipse.persistence.jpa.config.CacheUsage; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly); Example: @QueryHint import org.eclipse.persistence.jpa.config.CacheUsage; import org.eclipse.persistence.jpa.config.TargetDatabase; @QueryHint(name=EclipseLinkQueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheOnly); |
CacheUsage.UseEntityDefault Note: this default is DoNotCheckCache. |
eclipselink.query-type |
Specify the EclipseLink query type to use for the query. For most JP QL queries, the org.eclipse.persistence.queries.ReportQuery or org.eclipse.persistence.queries.ReadAllQuery are used. The eclipselink.query-type hint lets you use other query types, such as org.eclipse.persistence.queries.ReadObjectQuery for queries that are know to return a single object. For more information, see the following: The following are the valid values for the org.eclipse.persistence.jpa.config.QueryType:
import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.QUERY_TYPE, QueryType.ReadObject); Example: @QueryHint import org.eclipse.persistence.jpa.config.QueryType; import org.eclipse.persistence.jpa.config.TargetDatabase; @QueryHint(name=EclipseLinkQueryHints.QUERY_TYPE, value=QueryType.ReadObject); |
QueryType.Auto |
eclipselink.jdbc.bind-parameters |
Control whether or not the query uses parameter binding. For more information, see How to Use Parameterized SQL (Parameter Binding) and Prepared Statement Caching for Optimization. The following are the valid values for the org.eclipse.persistence.jpa.config.HintValues:
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.BIND_PARAMETERS, HintValues.TRUE); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.TargetDatabase; @QueryHint(name=EclipseLinkQueryHints.BIND_PARAMETERS, value=HintValues.TRUE); |
HintValues.PERSISTENCE_UNIT_DEFAULT |
eclipselink.jdbc.fetch-size |
Specify the number of rows that should be fetched from the database when more rows are needed. For large queries that return a large number of objects you can configure the row fetch size used in the query to improve performance by reducing the number database hits required to satisfy the selection criteria. Most JDBC drivers default to a fetch size of 10, so if you are reading 1000 objects, increasing the fetch size to 256 can significantly reduce the time required to fetch the query's results. The optimal fetch size is not always obvious. Usually, a fetch size of one half or one quarter of the total expected result size is optimal. Note that if you are unsure of the result set size, incorrectly setting a fetch size too large or too small can decrease performance. A value of 0 means the JDBC driver default will be used. Note: This property is dependent on the JDBC driver support. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String. |
0 Note: this value indicates that the JDBC driver default will be used. |
eclipselink.jdbc.timeout |
Specify the number of seconds EclipseLink will wait on a query before throwing a DatabaseException. A value of 0 means EclipseLink will never time-out a query. Note: This property is dependent on the JDBC driver support. Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String. |
0 |
eclipselink.pessimistic-lock |
Control whether or not pessimistic locking is used. The following are the valid values for the org.eclipse.persistence.jpa.config.PessimisticLock:
import org.eclipse.persistence.jpa.config.PessimisticLock; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait); Example: @QueryHint import org.eclipse.persistence.jpa.config.PessimisticLock; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.PESSIMISTIC_LOCK, value=PessimisticLock.LockNoWait); |
NoLock |
eclipselink.batch |
Supply EclipseLink with batching information so subsequent queries of related objects can be optimized in batches instead of being retrieved one-by-one or in one large joined read. Batch reading is more efficient than joining because it avoids reading duplicate data. Batching is only allowed on queries that have a single object in their select clause. Valid values: a single-valued relationship path expression. Note: Use dot notation to access nested attributes. For example, to batch-read an employee's manager's address, specify e.manager.address
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint("eclipselink.batch", "e.address"); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.BATCH, value="e.address"); |
"" |
eclipselink.join-fetch |
Allow joining of the attributes. This is similar to eclipselink.batch: subsequent queries of related objects can be optimized in batches instead of being retrieved in one large joined read. This is different from JP QL joining because it allows multilevel fetch joins. For more information, see Section 4.4.5.3 "Fetch Joins" of JPA specification. Valid values: a relationship path expression. Note: Use dot notation to access nested attributes.
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint("eclipselink.join-fetch", "e.address"); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.FETCH, value="e.address"); |
"" |
eclipselink.refresh |
Control whether or not to update the EclipseLink session cache with objects that the query returns. The following are the valid values for the org.eclipse.persistence.jpa.config.HintValues:
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.REFRESH, HintValues.TRUE); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.REFRESH, value=HintValues.TRUE); |
FALSE |
eclipselink.return-shared |
Retrieve read-only results back from the query: on nontransactional read operations, where the requested entity types are stored in the shared cache, you can request that the shared instance be returned instead of a detached copy. Note: You should never modify objects returned from the shared cache. The following are the valid values for the org.eclipse.persistence.jpa.config.HintValues:
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint(EclipseLinkQueryHints.RETURN_SHARED, HintValues.TRUE); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.RETURN_SHARED, value=HintValues.TRUE); |
FALSE |
eclipselink.result-collection-type |
Configure the concrete class that EclipseLink should use to return its query result. This lets you specify the type of collection in which the result will be returned. Valid values: Java Class that implements the Collection interface. Note: Typically, you would execute these queries by calling the getResultsList method, which returns the java.util.List, on the Query. This means that the class specified in this hint must implement the List interface, if you are invoking it using the getResultsList method. Note: Specify the class without the ".class" notation. For example, java.util.Vector would work, not java.util.Vector.classEclipseLink will throw an exception, if you use this hint with a class that does not implement the Collection interface.
import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; query.setHint("eclipselink.result-collection-type", java.util.ArrayList.class); Example: @QueryHint import org.eclipse.persistence.jpa.config.HintValues; import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints; @QueryHint(name=EclipseLinkQueryHints.RESULT_COLLECTION_TYPE, value="java.util.ArrayList"); |
java.util.Vector |
How to Use EclipseLink Query API in JPA Queries
EclipseLink JPA provides an EclipseLink implementation class for each JPA persistence interface. By casting to the EclipseLink implementation class, you have full access to EclipseLink functionality.
This section provides the following examples:
- Creating a JPA Query Using the EclipseLink Expressions Framework
- Creating a JPA Query Using an EclipseLink DatabaseQuery
- Creating a JPA Query Using an EclipseLink Call Object
- Using Named Parameters in a Native Query
- Using Java Persistence Query Language Positional Parameters in a Native Query
- Using JDBC-Style Positional Parameters in a Native Query
For more information, see Queries.
Creating a JPA Query Using the EclipseLink Expressions Framework
EclipseLink provides an expression framework with which you can express queries in a database-neutral fashion as an alternative to raw SQL.
This example shows how to cast an entity manager to access an EclipseLink persistence provider createQuery method that takes an EclipseLink Expression.
Creating a Query with the EclipseLink Expressions Framework
((org.eclipse.persistence.jpa.JpaEntityManager)entityManager.getDelegate()). createQuery(Expression expression, Class resultType);
EclipseLink expressions offer the following advantages over SQL when you access a database:
- Expressions are easier to maintain because the database is abstracted.
- Changes to descriptors or database tables do not affect the querying structures in the application.
- Expressions enhance readability by standardizing the Query interface so that it looks similar to traditional Java calling conventions.
For example, the Java code required to get the street name from the Address object of the Employee class looks like this:
emp.getAddress().getStreet().equals("Meadowlands");
The expression to get the same information is similar:
emp.get("address").get("street").equal("Meadowlands");
- Expressions allow read queries to transparently query between two classes that share a relationship. If these classes are stored in multiple tables in the database, EclipseLink automatically generates the appropriate join statements to return information from both tables.
- Expressions simplify complex operations.
For example, the following Java code retrieves all employees that live on "Meadowlands" whose salary is greater than 10,000:
ExpressionBuilder emp = new ExpressionBuilder(); Expression exp = emp.get("address").get("street").equal("Meadowlands"); Vector employees = session.readAllObjects(Employee.class, exp.and(emp.get("salary").greaterThan(10000)));
EclipseLink automatically generates the appropriate SQL from the preceding code:
SELECT t0.VERSION, t0.ADDR_ID, t0.EMP_ID, t0.SALARY FROM EMPLOYEE t0, ADDRESS t1 WHERE (((t1.STREET = 'Meadowlands')AND (t0.SALARY > 10000)) AND (t1.ADDRESS_ID = t0.ADDR_ID))
For more information, see Introduction to EclipseLink Expressions.
Creating a JPA Query Using an EclipseLink DatabaseQuery
An EclipseLink DatabaseQuery is a query object that provides a rich API for handling a variety of database query requirements, including reading and writing at the object level and at the data level.
For more information, see DatabaseQuery.
This example shows how to cast a JPA query from an entity manager to access an EclipseLink persistence provider setDatabaseQuery method that takes an EclipseLink DatabaseQuery.
DatabaseQuery
((org.eclipse.persistence.jpa.JpaQuery)query).setDatabaseQuery(DatabaseQuery query);
The following example shows how to cast a JPA query from an entity manager to access an EclipseLink persistence provider setDatabaseQuery method that takes an EclipseLink DataReadQuery initialized with an EclipseLink SQLCall object that specifies a SELECT. This query will return one or more objects.
DatabaseQuery with Selecting Call
((org.eclipse.persistence.jpa.JpaQuery)query). setDatabaseQuery(new DataReadQuery(new SQLCall("SELECT...")));
The following example shows how to cast a JPA query from an entity manager to access an EclipseLink persistence provider setDatabaseQuery method that takes an EclipseLink DataModifyQuery initialized with an EclipseLink SQLCall object that specifies an UPDATE. This query will modify one or more objects; however, this query will not update the managed objects within the persistence context.
DatabaseQuery with Non-Selecting Call
((org.eclipse.persistence.jpa.JpaQuery)query). setDatabaseQuery(new DataModifyQuery(new SQLCall("UPDATE...")));
Creating a JPA Query Using an EclipseLink Call Object
Using DatabaseQuery method setCall, you can define your own EclipseLink Call to accommodate a variety of data source options such as SQL stored procedures and stored functions, EJB QL queries, and EIS interactions.
This example shows how to cast a JPA query from an entity manager to access an EclipseLink persistence provider getDatabaseQuery method to set a new SQLCall.
Call
((org.eclipse.persistence.jpa.JpaQuery)query). getDatabaseQuery().setCall(new SQLCall("..."));
For more information, see Call Queries.
Using Named Parameters in a Native Query
Using EclipseLink, you can specify a named parameter in a native query using the EclipseLink # convention (see the Specifying a Named Parameter with # example).
Support for the EclipseLink # convention is helpful if you are already familiar with EclipseLink queries or if you are migrating EclipseLink queries to a JPA application.
Specifying a Named Parameter with #
Query queryEmployees = entityManager.createNativeQuery( "SELECT * FROM EMPLOYEE emp WHERE emp.fname LIKE #firstname"); queryEmployees.setParameter("firstName", "Joan"); Collection employees = queryEmployees.getResultList();
Using JP QL Positional Parameters in a Native Query
Using EclipseLink, you can specify positional parameters in a native query using the Java Persistence query language (JP QL) positional parameter convention ?n to specify a parameter by number. For more information on JP QL, see What You May Need to Know About Querying with Java Persistence Query Language.
This example shows how to specify positional parameters using the ?n convention. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "C%".
Specifying Positional Parameters Using ?
Query queryEmployees = entityManager.createNativeQuery( "SELECT * FROM EMPLOYEE WHERE F_NAME LIKE ?1 AND L_NAME LIKE ?2", Employee.class); queryEmployees.setParameter(1, "D%"); queryEmployees.setParameter(2, "C%"); Collection employees = queryEmployees.getResultList();
You can easily re-use the same parameter in more than one place in the query, as the following example shows. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "D%".
Specifying Positional Parameters Using ?n
Query queryEmployees = entityManager.createNativeQuery( "SELECT * FROM EMPLOYEE WHERE F_NAME LIKE ?1 AND L_NAME LIKE ?1", Employee.class); queryEmployees.setParameter(1, "D%"); Collection employees = queryEmployees.getResultList();
Using JDBC-Style Positional Parameters in a Native Query
Using EclipseLink, you can specify positional parameters in a native query using the JDBC-style positional parameter ? convention.
This example shows how to specify positional parameters using the ? convention. Each occurrence of ? must be matched by a corresponding setParameter call. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "C%".
Specifying Positional Parameters with ?
Query queryEmployees = entityManager.createNativeQuery( "SELECT * FROM EMPLOYEE WHERE F_NAME LIKE ? AND L_NAME LIKE ?", Employee.class); queryEmployees.setParameter(1, "D%"); queryEmployees.setParameter(2, "C%"); Collection employees = queryEmployees.getResultList();
If you want to re-use the same parameter in more than one place in the query, you must repeat the same parameter, as this example shows. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "D%".
Re-Using Positional Parameters with ?
Query queryEmployees = entityManager.createNativeQuery( "SELECT * FROM EMPLOYEE WHERE F_NAME LIKE ? AND L_NAME LIKE ?", Employee.class); queryEmployees.setParameter(1, "D%"); queryEmployees.setParameter(2, "D%"); Collection employees = queryEmployees.getResultList();
Using EclipseLink JPA Weaving
Weaving is a technique of manipulating the byte-code of compiled Java classes. The EclipseLink JPA persistence provider uses weaving to enhance JPA entities for such things as lazy loading, change tracking, fetch groups, and internal optimizations.
This section describes the following:
- How to Configure Dynamic Weaving for JPA Entities Using the EclipseLink Agent
- How to Configure Static Weaving for JPA Entities
- How to Disable Weaving Using EclipseLink Persistence Unit Properties
- What You May Need to Know About Weaving JPA Entities
How to Configure Dynamic Weaving for JPA Entities Using the EclipseLink Agent
Use this option to weave applicable class files one at a time, as they are loaded at run time. Consider this option when the number of classes to weave is few or the time taken to weave the classes is short.
If the number of classes to weave is large or the time required to weave the classes is long, consider using static weaving. For more information, see How to Configure Static Weaving for JPA Entities.
To Configure Dynamic Weaving for JPA Entities Using the EclipseLink Agent
- Configure your persistence.xml file with a persistence.tools.weaving extension set to true, as this example shows.
Setting persistence.tools.weaving in the persistence.xml File
<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="persistence.tools.weaving" value="true" > </properties> </persistence-unit> </persistence>
For more information, see the EclipseLink JPA Persistence Unit Properties for Customization and Validation table. - Modify your application JVM command line to include the following:
-javaagent:eclipselink-agent.jar
- Ensure that the eclipselink-agent.jar is in your application classpath.
|and deploy your application.
For more information, see Packaging an EclipseLink JPA Application.
EclipseLink weaves applicable class files one at a time, as they are loaded at run time.
How to Configure Static Weaving for JPA Entities
Use this option to weave all applicable class files at build time so that you can deliver pre-woven class files. Consider this option to weave all applicable class files at build time so that you can deliver prewoven class files. By doing so, you can improve application performance by eliminating the runtime weaving step required by dynamic weaving (see How to Configure Dynamic Weaving for JPA Entities Using the EclipseLink Agent).
In addition, consider using this option to weave in Java environments where you cannot configure an agent.
To Configure Static Weaving for JPA Entities
- Execute the static static weaver in one of the following ways:
- Use the weave Ant task as follows:
- Configure the weave Ant task in your build script, as this example shows. The EclipseLink weave Ant Task Attributes tablelists the attributes of this task.
EclipseLink weave Ant Task<target name="define.task" description="New task definition for EclipseLInk static weaving"/> <taskdef name="weave" classname="org.eclipse.persistence.tools.weaving.StaticWeaveAntTask"/> </target> <target name="weaving" description="perform weaving" depends="define.task"> <weave source="c:\myjar.jar" target="c:\wovenmyjar.jar" persistenceinfo="c:\myjar-containing-persistenceinfo.jar"> <classpath> <pathelement path="c:\myjar-dependent.jar"/> </classpath> </weave> </target>
EclipseLink weave Ant Task AttributesAttribute Description Default Required or Optional source
Specifies the location of the Java source files to weave: either a directory or a JAR file.
If the persistence.xml file is not in this location, you must specify the location of the persistence.xml using the persistenceinfo attribute.
Required
target
Specifies the output location: either a directory or a JAR file.
Required
persistenceinfo
Specifies the location of the persistence.xml file if it is not in the same location as the source.
Optional
log
Specifies a logging file.
See Logging.
Optional
loglevel
Specifies the amount and detail of log output.
Valid java.util.logging.Level values are the following:
- OFF
- SEVERE
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST
For more information, see Logging.
Level.OFF
Optional
Note: If source and target point to the same location and, if the source is a directory (not a JAR file), EclipseLink will weave in place. If source and target point to different locations or if the source is a JAR file (as the EclipseLink weave Ant Task example shows), EclipseLink cannot weave in place.
- Configure the weave task with an appropriate <classpath> element, as the EclipseLink weave Ant Task example shows, so that EclipseLink can load all required source classes.
- Execute the Ant task using the command line that this example shows.
In this example, the weave Ant task is in the build.xml file: EclipseLink weave Ant Task Command Lineant -lib C:\eclipselink.jar -f build.xml weave
Note: You must specify the eclipselink.jar file (the JAR that contains the EclipseLink weave Ant task) using the Ant command line -lib option instead of using the taskdef attribute classpath.
- Configure the weave Ant task in your build script, as this example shows. The EclipseLink weave Ant Task Attributes tablelists the attributes of this task.
- Use the command line as follows:
java org.eclipse.persistence.tools.weaving.StaticWeave [arguments] <source> <target>
This example shows how to use the StaticWeave class on Windows systems. The EclipseLink StaticWeave Class Command Line Arguments tablelists the arguments of this class.
Executing StaticWeave on the Command Linejava org.eclipse.persistence.tools.weaving.StaticWeave -persistenceinfo c:\myjar-containing-persistencexml.jar -classpath c:\classpath1;c:\classpath2 c:\myjar-source.jar c:\myjar-target.jar
EclipseLink StaticWeave Class Command Line Arguments
Argument Description Default Required or Optional -persistenceinfo
Specifies the location of the persistence.xml file if it is not in the same location as the source (see-classpath).
Optional
-classpath
Specifies the location of the Java source files to weave: either a directory or a JAR file. For Windows systems, use delimiter " ; " and for Unix, use delimiter " : ".
If the persistence.xml file is not in this location, you must specify the location of the persistence.xml using the -persistenceinfo attribute.
Required
-log
Specifies a logging file.
See Logging.
Optional
-loglevel
Specifies the amount and detail of log output.
Valid java.util.logging.Level values are as follows:
- OFF
- SEVERE
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST
For more information, see Logging.
Level.OFF
Optional
<source>
Specifies the location of the Java source files to weave: either a directory or a JAR file.
If the persistence.xml file is not in this location, you must specify the location of the persistence.xml using the -persistenceinfo attribute.
Required
<target>
Specifies the output location: either a directory or a JAR file.
Required
Note: If <source> and <target> point to the same location and if the <source> is a directory (not a JAR file), EclipseLink will weave in place. If <source> and <target> point to different locations or if the source is a JAR file (as the Executing StaticWeave on the Command Line example shows), EclipseLink cannot weave in place.
- Use the weave Ant task as follows:
- Configure your persistence.xml file with a persistence.tools.weaving extension set to static, as this example shows.
Setting persistence.tools.weaving in the persistence.xml File<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="persistence.tools.weaving" value="static" > </properties> </persistence-unit> </persistence>
For more information, see the EclipseLink JPA Persistence Unit Properties for Customization and Validation table. - Package and deploy your application.
For more information, see Packaging and Deploying EclipseLink JPA Applications.
How to Disable Weaving Using EclipseLink Persistence Unit Properties
To disable weaving, you use persistence unit properties.
To Disable Weaving Using EclipseLink Persistence Unit Properties
- Configure your persistence.xml file with one or more of the following properties set to false:
- persistence.tools.weaving – disables all weaving;
- persistence.tools.weaving.lazy – disables weaving for lazy loading (indirection);
- persistence.tools.weaving.changetracking – disables weaving for change tracking;
- persistence.tools.weaving.fetchgroups – disables weaving for fetch groups.
Disabling Weaving for Change Tracking in the persistence.xml File<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="persistence.tools.weaving.changetracking" value="false" > </properties> </persistence-unit> </persistence>
The following example shows how to disable all weaving: in this example, EclipseLink does not weave for lazy loading (indirection), change tracking, or internal optimization.
Disabling All Weaving in the persistence.xml File
<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="persistence.tools.weaving" value="false" > </properties> </persistence-unit> </persistence>
For more information, see the EclipseLink JPA Persistence Unit Properties for Customization and Validation table.
- Package and and deploy your application. For more information, see Packaging and Deploying EclipseLink JPA Applications.
What You May Need to Know About Weaving JPA Entities
The EclipseLink JPA persistence provider uses weaving to enable the following features for JPA entities:
- lazy loading (indirection): see How to Configure Lazy Loading;
- change tracking: see How to Configure Change Tracking;
- fetch groups: see How to Configure Fetch Groups;
- internal optimizations: see Optimizing the EclipseLink Application.
EclipseLink weaves all the JPA entities in a given persistence unit. That is the following:
- all classes you list in persistence.xml file;
- if element <exclude-unlisted-classes> is false, or deployed in Java EE, all classes in the JAR file containing the persistence.xml file;
- all classes you list in the orm.xml file.
For more information, see What You May Need to Know About Weaving and Java EE Application Servers.
What You May Need to Know About EclipseLink JPA Lazy Loading
JPA specifies that lazy loading is a hint to the persistence provider that data should be fetched lazily when it is first accessed, if possible.
If you are developing your application in a Java EE environment, you only have to set fetch to javax.persistence.FetchType.LAZY, and EclipseLink persistence provider will supply all the necessary functionality.
When using a one-to-one (see @OneToOne) or many-to-one (see @ManyToOne) mapping in a Java SE environment, to configure EclipseLink JPA to perform lazy loading when the fetch attribute is set to FetchType.LAZY, configure either dynamic or static weaving.
When using a one-to-one (see @OneToOne) or many-to-one (see @ManyToOne) mapping in a Java SE environment that permits the use of -javaagent on the JVM command line, to configure EclipseLink JPA to perform lazy loading when the annotation attribute fetch is set to javax.persistence.FetchType.LAZY, you can use the eclipselink-agent.jar to configure dynamic weaving.
When using a one-to-one (see @OneToOne) or many-to-one (see @ManyToOne) mapping in a Java SE environment that does not permit the use of -javaagent on the JVM command line, to configure EclipseLink JPA to perform lazy loading when annotation attribute fetch is set to javax.persistence.FetchType.LAZY, you can use static weaving.
The EclipseLink JPA Support for Lazy Loading by Mapping Type table lists EclipseLink JPA support for lazy loading by mapping type.
For more information, see the following:
- How to Configure Dynamic Weaving for JPA Entities Using the EclipseLink Agent
- How to Configure Static Weaving for JPA Entities
- How to Disable Weaving Using EclipseLink Persistence Unit Properties
- What You May Need to Know About Weaving JPA Entities
- Configuring Indirection (Lazy Loading)
EclipseLink JPA Support for Lazy Loading by Mapping Type
Mapping | Java EE 1 | Java SE |
---|---|---|
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (default). |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (default). | |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (default). |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (default). | |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY. |
By default, EclipseLink JPA ignores the fetch attribute and default javax.persistence.FetchType.EAGER applies. To configure EclipseLink JPA to perform lazy loading when the fetch attribute set to FetchType.LAZY, consider one of the following: | |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY. |
By default, EclipseLink JPA ignores the fetch attribute and default javax.persistence.FetchType.EAGER applies.To configure EclipseLink JPA to perform lazy loading when the fetch attribute set to FetchType.LAZY, configure one of the following: | |
EclipseLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY. |
By default, EclipseLink JPA ignores the fetch attribute and default javax.persistence.FetchType.EAGER applies. To configure EclipseLink JPA to perform lazy loading when the fetch attribute set to FetchType.LAZY, consider one of the following: |
1 Fully supported in any container that implements the appropriate container contracts in the EJB 3.0 specification.
What You May Need to Know About Overriding Annotations in JPA
In JPA, you override any annotation with XML in your object relational mapping files (see Overriding Annotations with XML).
In EclipseLink JPA, you either use JPA processing, or you specify the sessions.xml file resulting in creation of the project.xml file. For more information, see What You May Need to Know About EclipseLink JPA Overriding Mechanisms.
Overriding Annotations with XML
In JPA, you can use XML mapping metadata on its own, or in combination with annotation metadata, or you can use it to override the annotation metadata.
If you choose to include one or more mapping XML files in your persistence unit, each file must conform and be valid against the orm_1_0.xsd schema located at http://java.sun.com/xml/ns/persistence/orm_1_0.xsd. This schema defines a namespace called http://java.sun.com/xml/ns/persistence/orm that includes all of the ORM elements that you can use in your mapping file.
All object relational XML metadata is contained within the entity-mappings root element of the mapping file. The subelements of entity-mappings can be categorized into four main scoping and functional groups: persistence unit defaults, mapping file defaults, queries and generators, and managed classes and mappings. There is also a special setting that determines whether annotations should be considered in the metadata for the persistence unit (see Disabling Annotations).
For more information and examples, see Section 10.1 "XML Overriding Rules" of the JPA Specification.
Disabling Annotations
JPA provides a mechanism that you can use to disable annotations. If you do not feel the need for annotations in your application, you can use the xml-mapping-metadata-complete and metadata-complete mapping file elements to disable any existing annotations. Setting this options causes the processor to completely ignore annotations.
When you specify the xml-mapping-metadata-complete element, all annotations in the persistence unit will be ignored, and only mapping files in the persistence unit will be considered as the total set of provided metadata. Only entities (see Section 8.1 "Entity" of the JPA Specification), mapped superclasses (see @MappedSuperclass), and embedded objects (see @Embedded) that have entries in a mapping file will be added to the persistence unit. The xml-mapping-metadata-complete element has to be in only one of the mapping files in the persistence unit. You specify it as an empty subelement of the persistence-unit-metadata element, as this example shows:
Disabling Annotations for the Persistence Unit in the Mapping File
<entity-mappings> <persistence-unit-metadata> <xml-mapping-metadata-complete/> </persistence-unit-metadata> ... </entity-mappings>
You can also use the metadata-complete attribute of the entity, mapped-superclass, and embeddable elements. If you specify this attribute, all annotations on the specified class and on any fields or properties in the class will be ignored – only metadata in the mapping file will be considered as the set of metadata for the class. However, even though the annotations are ignored, the default mapping still applies, so any fields or properties that should not be mapped must still be marked as transient in the XML file, as this example demonstrates.
Disabling Annotations for a Managed Class in the Mapping File
@Entity public class Employee { @Id private int id; @Column(name="EMP_NAME") private String name; @Column(name="SALARY") private long salary; ... } <entity-mappings> ... <entity class="mypackage.Employee" metadata-complete="true"> <attributes> <id name="id"/> </attributes> </entity> ... </entity-mappings>
In the preceding example, the entity mappings in the annotated class are disabled by the metadata-complete attribute, and because the fields are not mapped in the mapping file, the default mapping values will be used. The name and salary fields will be mapped to the NAME and SALARY columns, respectively.
For more information, see Section 10.1 "XML Overriding Rules" of the JPA Specification.
Advantages and Disadvantages of Using Annotations
Metadata annotations are relatively simple to use and understand. They provide in-line metadata located with the code that this metadata is describing – you do not need to replicate the source code context of where the metadata applies.
On the other hand, annotations unnecessarily couple the metadata to the code. Thus, changes to metadata require changing the source code.
Advantages and Disadvantages of Using XML
The following are the advantages of using XML:
- no coupling between the metadata and the source code;
- compliance with the existing, pre-EJB 3.0 development process;
- support in IDEs and source control systems.
The main disadvantages of mapping with XML are the complexity and the need for replication of the code context.
What You May Need to Know About EclipseLink JPA Overriding Mechanisms
EclipseLink JPA provides a set of persistence unit properties (see What you May Need to Know About Using EclipseLink JPA Persistence Unit Properties) that you can specify in your persistence.xml file. The persistence unit properties always override the corresponding annotations' attributes.
Similar to EclipseLink annotations, properties expose some features of EclipseLink that are currently not available through the use of JPA metadata.
Note: If multiple instances of the same property are set, then EclipseLink will use the values from the last entry in the list. However, the properties Map provided in the createEntityManagerFactory method will always have precedence. |
You can also specify the persistence information in the EclipseLink session configuration file – sessions.xml (see Session Configuration and the sessions.xml File). By setting the eclipselink.sessions-xml persistence unit property you enable EclipseLink to replace all class annotations and object relational mappings that you defined in the persistence.xml file, as well as mapping files (if present). Through the sessions.xml file the eclipselink.sessions-xml property lets you provide session-level configurations that are not supported by persistence unit properties (for example, cache coordination).
Note: You can use the eclipselink.sessions-xml property as an alternative to annotations and deployment XML. |
For more information on creating and configuring the sessions.xml file, see the following:
- Acquiring a Session at Run Time with the Session Manager
- Building and Using the Persistence Layer
- Loading project.xml or sessions.xml Files
- Development Environment
- Introduction to the EclipseLink Deployment File Creation
- Packaging an EclipseLink Application
- EclipseLink Sessions XML File
- Introduction to the Session Creation
- Creating a Sessions Configuration
- Configuring a Sessions Configuration
- Introduction to Session Acquisition
In summary, EclipseLink JPA possesses an overriding mechanism that you can use in the following ways:
- You can combine the use of JPA annotations, object relational mapping files (such as orm.xml) and persistence unit properties.In this case, EclipseLink persistence provider builds metadata starting with applying defaults, then JPA annotations, and then overrides that with elements of the object relational mapping file. This results in creation of an in-memory EclipseLink session and project. Then EclipseLink persistence provider applies persistence unit properties specified in persistence.xml file, as the following illustration shows.
Note: The eclipselink.sessions-xml property represents a special case discussed further. |
Combining the Use of Annotations, orm.xml File and Persistence Unit Properties
- You can use the eclipselink.sessions-xml persistence unit property.This defines a sessions.xml file, which references a project.xml file. In this case, EclipseLink persistence provider builds an in-memory EclipseLink session and project based on this metadata, as the following illustration shows. You can acquire a persistence manager and use it as per the JPA specification, having defined all entities and so on using only EclipseLink sessions.xml (see Creating Session Metadata) and project.xml files that you created Workbench (see Creating the project.xml File with Workbench|Creating the project.xml File with Workbench).
Using eclipselink.sessions-xml Persistence Unit Property
Note: You cannot combine the use of JPA annotations, object relational mapping files, persistence unit properties and the eclipselink.sessions-xml persistence unit property. |
What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties
A persistence unit configures various details that are required when you acquire an entity manager. You specify a persistence unit by name when you acquire an entity manager factory.
You configure persistence units in JPA persistence descriptor file persistence.xml.
In this file, you can specify the vendor extensions that this reference describes by using a <properties> element. The Configuring a Vendor Extension in the persistence.xml File (Java EE) example shows how to set an EclipseLink JPA persistence unit extension in a persistence.xml file for a Java EE application. The Configuring a Vendor Extension in the persistence.xml File (Java SE) example shows how to do the same for a Java SE application.
Configuring a Vendor Extension in the persistence.xml File (Java EE)
<persistence-unit name="default" transaction-type="JTA"> <provider> org.eclipse.persistence.jpa.PersistenceProvider </provider> <jta-data-source> jdbc/MyDataSource </jta-data-source> <properties> <property name="eclipselink.logging.level" value="INFO"/> </properties> </persistence-unit>
Configuring a Vendor Extension in the persistence.xml File (Java SE)
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL"> <provider> org.eclipse.persistence.jpa.PersistenceProvider </provider> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="eclipselink.logging.level" value="INFO"/> <property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver"/> <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@myhost:1521:MYSID"/> <property name="eclipselink.jdbc.password" value="tiger"/> <property name="eclipselink.jdbc.user" value="scott"/> </properties> </persistence-unit>
Alternatively, you can set a vendor extensions in the Map of properties you pass into a call to javax.persistence.Persistence method createEntityManagerFactory, asthe Configuring a Vendor Extension when Creating an EntityManagerFactory example shows. You can override extensions set in the persistence.xml file in this way. When you set an extension in a map of properties, you can set the value using the public static final field in the appropriate configuration class in org.eclipse.persistence.jpa.config, including the following:
- CacheType
- TargetDatabase
- TargetServer
- PersistenceUnitProperties
The following example shows how to set the value of extension eclipselink.cache.type.default using the CacheType configuration class.
Configuring a Vendor Extension when Creating an EntityManagerFactory
import org.eclipse.persistence.jpa.config.CacheType; Map properties = new HashMap(); properties.put(PersistenceUnitProperties.CACHE_TYPE_DEFAULT, CacheType.Full); EntityManagerFactory emf = Persistence.createEntityManagerFactory("default", properties);
You may specify any EclipseLink JPA extension in a persistence.xml file and you may pass any EclipseLink JPA extension into Persistence method createEntityManagerFactory.
Currently, no EclipseLink JPA extensions are applicable to EntityManagerFactory method createEntityManager.
For more information, see the following:
- Section 2.1 "Requirements on the Entity Class" of the JPA Specification;
- Chapter 5 "Entity Managers and Persistence Contexts" of the JPA Specification.