Using EclipseLink JPA Extensions (ELUG)
Contents
- 1 Using EclipseLink JPA Extensions for Mapping
- 1.1 How to Use the @BasicCollection Annotation
- 1.2 How to Use the @BasicMap Annotation
- 1.3 How to Use the @CollectionTable Annotation
- 1.4 How to Use the @PrivateOwned Annotation
- 1.5 How to Use the @JoinFetch Annotation
- 1.6 How to Use the @Mutable Annotation
- 1.7 How to Use the @Transformation Annotation
- 1.8 How to Use the @ReadTransformer Annotation
- 1.9 How to Use the @WriteTransformer Annotation
- 1.10 How to Use the @WriteTransformers Annotation
- 1.11 How to Use the @VariableOneToOne Annotation
- 1.12 How to Use the Persistence Unit Properties for Mappings
- 2 Using EclipseLink JPA Converters
- 3 Using EclipseLink JPA Extensions for Entity Caching
- 4 Using EclipseLink JPA Extensions for Customization and Optimization
- 5 Using EclipseLink JPA Extensions for Copy Policy
- 6 Using EclipseLink JPA Extensions for Declaration of Read-Only Classes
- 7 Using EclipseLink JPA Extensions for Returning Policy
- 8 Using EclipseLink JPA Extensions for Optimistic Locking
- 9 Using EclipseLink JPA Extensions for Stored Procedure Query
- 10 Using EclipseLink JPA Extensions for JDBC
- 11 Using EclipseLink JPA Extensions for Logging
- 12 Using EclipseLink JPA Extensions for Session, Target Database and Target Application Server
- 13 Using EclipseLink JPA Extensions for Schema Generation
- 14 Using EclipseLink JPA Extensions for Tracking Changes
- 15 Using EclipseLink JPA Query Customization Extensions
- 15.1 How to Use EclipseLink JPA Query Hints
- 15.2 How to Use EclipseLink Query API in JPA Queries
- 15.2.1 Creating a JPA Query Using the EclipseLink Expressions Framework
- 15.2.2 Creating a JPA Query Using an EclipseLink DatabaseQuery
- 15.2.3 Creating a JPA Query Using an EclipseLink Call Object
- 15.2.4 Using Named Parameters in a Native Query
- 15.2.5 Using JP QL Positional Parameters in a Native Query
- 15.2.6 Using JDBC-Style Positional Parameters in a Native Query
- 16 Using EclipseLink JPA Weaving
- 17 What You May Need to Know About EclipseLink JPA Lazy Loading
- 18 What You May Need to Know About Overriding Annotations in JPA
- 19 What You May Need to Know About EclipseLink JPA Overriding Mechanisms
- 20 What You May Need to Know About Using EclipseLink JPA Persistence Unit Properties
- 21 Avoiding Cleartext Passwords
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):
- @BasicCollection
- @BasicMap
- @CollectionTable
- @PrivateOwned
- @JoinFetch
- @Mutable
- @Transformation
- @ReadTransformer
- @WriteTransformer
- @WriteTransformers
- @VariableOneToOne
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 { FetchType fetch() default LAZY; Column valueColumn() default @Column; }
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 { FetchType fetch() default LAZY; Column keyColumn(); Convert keyConverter() default @Convert; Column valueColumn() default @Column; Convert valueConverter() default @Convert; }
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) |
optional |
keyConverter |
Set this attribute to the key converter (@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 (@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") ) @ObjectTypeConverter( 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, 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 or 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 { String name() default ""; String catalog() default ""; String schema() default ""; PrimaryKeyJoinColumn[] primaryKeyJoinColumns() default {}; UniqueConstraint[] uniqueConstraints() default {}; }
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<PhoneNumber> 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 { JoinFetchType value() default JoinFetchType.INNER; }
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:
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<Employee> getManagedEmployees() { return managedEmployees; } ... }
How to Use the @Mutable Annotation
You can specify the @Mutable annotation for the following mappings:
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Mutable { boolean value() default true; }
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:
|
true |
optional |
This example shows how to use the @Mutable annotation to specify Employee field hireDate.
Usage of the @Mutable Annotation
@Entity public class Employee implements Serializable { ... @Temporal(DATE) @Mutable public Calendar getHireDate() { return hireDate; } ... }
How to Use the @Transformation Annotation
You can use the @Transformation annotation to map an org.eclipse.persistence.mappings.TransformationMapping, which allows to map an attribute to one or more database columns.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Transformation { FetchType fetch() default EAGER; boolean optional() default true; }
Note: The @Transformation annotation is optional for transformation mappings: if you specify either a @ReadTransformer, @WriteTransformer or @WriteTransformers annotation, the mapping would become a transformation mapping by default, without you specifying the @Transformation annotation. |
This table lists attributes of the @Transformation annotation.
Attributes of the @Transformation 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.EAGER |
optional |
optional |
Set this attribute to define whether or not the value of the field or property may be null. Note: the value you set is disregarded for primitive types, which are considered mandatory. The following are valid values:
|
true |
optional |
For more information, see the following:
Annotation
How to Use the @ReadTransformer Annotation
Use the @ReadTransformer annotation with the @Transformation mapping to define transformation of one or more database column values into an attribute value. Note that you can only use this annotation if the @Transformation mapping is not write-only.
@Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface ReadTransformer { Class transformerClass() default void.class; String method() default ""; }
This table lists attributes of the @ReadTransformer annotation.
Attributes of the @ReadTransformer Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
method |
Set this attribute to the String method name that the mapped class must have. This method does not assign a value to the attribute; instead, it returns the value to be assigned to the attribute. |
empty String |
required/optional1 |
transformerClass |
Set this attribute to the Class that implements the org.eclipse.persistence.mappings.transformers.AttributeTransformer interface. This will instantiate the class and use its buildAttributeValue method to create the value to be assigned to the attribute. For more information, see see How to Configure Attribute Transformer Using Java. |
void.class |
required/optional1 |
1 You must specify either the transformerClass or method, but not both
How to Use the @WriteTransformer Annotation
Use the @WriteTransformer annotation with the @Transformation mapping to define transformation of an attribute value to a single database column value. Note that you can only use this annotation if the @Transformation mapping is not read-only.
@Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface WriteTransformer { Class transformerClass() default void.class; String method() default ""; Column column() default @Column; }
This table lists attributes of the @WriteTransformer annotation.
Attributes of the @WriteTransformer Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
method |
Set this attribute to the String method name that the mapped class must have. This method returns the value to be written into the database column. Note: for proper support of DDL generation and returning policy, define the method to return not just an Object, but a particular type, as the following example shows: public Time getStartTime() The method may require a @Transient annotation to avoid being mapped as the @Basic by default. |
empty String |
required/optional 1 |
transformerClass |
Set this attribute to the Class that implements the org.eclipse.persistence.mappings.transformers.FieldTransformer interface. This will instantiate the class and use its buildFieldValue method to create the value to be written into the database column. For more information, see see How to Configure Field Transformer Associations. Note: for proper support of DDL generation and returning policy, define the method to return not just an Object, but a relevant Java type, as the following example shows: public Time buildFieldValue(Object instance, String fieldName, Session session) |
void.class |
required/optional 1 |
column |
Set this attribute to a Column into which the value should be written. You may choose not to set this attribute if a single WriteTransformer annotates an attribute. In this case, the attribute's name will be used as a column name. |
@javax.persistence.Column (see Section 9.1.5 "Column Annotation" of the JPA specification) |
required |
1 You must specify either the transformerClass or method, but not both.
How to Use the @WriteTransformers Annotation
Use the @WriteTransformers annotation with the @Transformation mapping to wrap multiple write transformers. Note that you can only use this annotation if the @Transformation mapping is not read-only.
@Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface WriteTransformers { WriteTransformer[] value(); }
This table lists attributes of the @WriteTransformers annotation.
Attributes of the @WriteTransformers Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the array of WriteTransformer. |
no default |
optional |
How to Use the @VariableOneToOne Annotation
You can use the @VariableOneToOne annotation to map an org.eclipse.persistence.mappings.VariableOneToOneMapping, which you use to represent a pointer references between a Java object and an implementer of an interface. This mapping is typically represented by a single pointer (stored in an instance variable) between the source and target objects. In the relational database tables, these mappings are usually implemented using a foreign key and a type code.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface VariableOneToOne { Class targetInterface() default void.class; CascadeType[] cascade() default {}; FetchType fetch() default EAGER; boolean optional() default true; DiscriminatorColumn discriminatorColumn() default @DiscriminatorColumn; DiscriminatorClass[] discriminatorClasses() default {}; }
Specify the @VariableOneToOne annotation within an @Entity (see Section 8.1 "Entity" of the JPA Specification), @MappedSuperclass or @Embeddable class.
This table lists attributes of the @VariableOneToOne annotation.
Attributes of the @VariableOneToOneAnnotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
cascade |
Set this attribute to an array of javax.persistence.CascadeType objects to indicate operations that must be cascaded to the target of the association. |
{} |
optional |
discriminatorClasses |
Set this attribute to an array of org.eclipse.persistence.annotations.DiscriminatorClass objects to provide a list of discriminator types that can be used with this variable one-to-one mapping. If none are specified, then those entities within the persistence unit that implement the target interface will be added to the list of types. In this case, the discriminator type will default as follows:
|
{} |
optional |
discriminatorColumn |
Set this attribute to the javax.persistence.DiscriminatorColumn that will hold the type indicators. If the discriminator column is not specified, the name of the discriminator column defaults to "DTYPE", and the discriminator type - to STRING. |
@javax.persistence.DiscriminatorColumn |
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.EAGER |
optional |
optional |
Set this attribute to define whether or not the association is optional. The following are valid values:
|
true |
optional |
targetInterface |
Set this attribute to an interface class that is the target of the association. If not specified, it will be inferred from the type of the object being referenced. |
void.class |
optional |
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.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 the following:
- What you May Need to Know About Overriding Annotations in JPA
- 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:
- @Convert
- @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
You can use EclipseLink converters with the following mappings:
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 { String name(); Class converterClass(); }
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 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 { String name(); Class dataType() default void.class; Class objectType() default void.class; }
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.class1 |
optional |
objectType |
Set the value of this attribute to the type stored on the entity. |
void.class1 |
optional |
1 The default is inferred from the type of the persistence field or property.
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; } ... }
- Another example of TypeConverter usage is in the distributed tutorial - this one is used to enable storage of a near limitless BigInteger using a String (VARCHAR) field instead of the usual NUMBER type.
How to Use the @ObjectTypeConverter Annotation
You can use the @ObjectTypeConverter annotation to specify an org.eclipse.persistence.mappings.converters.ObjectTypeConverter that converts a fixed number of database data value(s) to Java object value(s) during the reading and writing of a mapped attribute.
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface ObjectTypeConverter { String name(); Class dataType() default void.class; Class objectType() default void.class; ConversionValue[] conversionValues(); String defaultObjectValue() default ""; }
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.class1 |
optional |
objectType |
Set the value of this attribute to the type stored on the entity. |
void.class1 |
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 |
1 The default is inferred from the type of the persistence field or property.
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 { String name(); String converter(); }
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. 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 { String value() default "none"; }
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 the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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 { CacheType type() default SOFT_WEAK; int size() default 100; boolean shared() default true; int expiry() default -1; TimeOfDay expiryTimeOfDay() default @TimeOfDay(specified=false); boolean alwaysRefresh() default false; boolean refreshOnlyIfNewer() default false; boolean disableHits() default false; CacheCoordinationType coordinationType() default SEND_OBJECT_CHANGES; }
You may define the @Cache annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @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 |
|
size |
Set this attribute to an int value to define the size of cache to use (number of objects). |
100 |
|
|
shared |
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). The following are the valid values:
|
true |
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 use in a persistence.xml file and for the org.eclipse.persistence.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.config.CacheType; import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_TYPE_DEFAULT, CacheType.Full); |
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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SIZE_DEFAULT, 5000); |
100 |
|
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="false"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, "false"); |
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 use in a persistence.xml file and for the org.eclipse.persistence.config.CacheType:
<property name="eclipselink.cache.type.Order" value="Full"/> Example: property Map import org.eclipse.persistence.config.CacheType; import org.eclipse.persistence.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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SIZE+".Order", 1000); |
eclipselink.cache.size.default |
|
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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_SHARED+".Order", "true"); |
eclipselink.cache.shared.default |
eclipselink.flush-clear.cache |
Defines the EntityManager cache behaviour after a call to the flush method followed by a call to the clear method. You can specify this property while creating either an EntityManagerFactory (either in the map passed to the createEntityManagerFactory method, or in the persistence.xml file), or an EntityManager (in the map passed to the createEntityManager method). Note that the latter overrides the former. The following are the valid values for the use in a persistence.xml file and for the org.eclipse.persistence.config.FlushClearCache:
<property name="eclipselink.flush-clear.cache" value="Drop"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, FlushClearCache.Drop); |
DropInvalidate |
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 { int hour() default 0; int minute() default 0; int second() default 0; int millisecond() default 0; }
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 |
How to Use the @ExistenceChecking Annotation
Use the @ExistenceChecking annotation to specify the type of checking that EclipseLink should use when determining if an Entity is new or already existing.
On a merge operation, this annotation determines whether or not EclipseLink should only use the cache to check if an object exists, or should read the object (from the database or cache).
@Target({TYPE}) @Retention(RUNTIME) public @interface ExistenceChecking { ExistenceType value() default CHECK_CACHE; }
You may define the @ExistenceChecking annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass;
This table lists attributes of the @ExistenceChecking annotation.
Attributes of the @ExistenceChecking Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the type (org.eclipse.persistence.annotations.ExistenceType enumerated type) of the existence checking that you will be using to determine if an insert or an update operation should occur for an object. The following are the valid values for the ExistenceType:
|
One of the following default values applies:
|
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 the following: |
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.config.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 { Class value(); }
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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.ECLIPSELINK_ORM_THROW_EXCEPTIONS, "false"); |
true |
eclipselink.exception-handler |
Specify an EclipseLink exception handler class: a Java class that implements the org.eclipse.persistence.exceptions.ExceptionHandler interface and provides a default (zero-argument) constructor. Use this class’ handleException method, which takes a java.lang.RuntimeException, to rethrow the exception, throw a different exception, or retry a query or a database operation. For more information, see Exception Handlers. Valid values: class name of an ExceptionHandler class fully qualified by its package name.
<property name="eclipselink.exception-handler" value="my.package.MyExceptionHandler"> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, "my.package.MyExceptionHandler"); |
|
eclipselink.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:
This assumes that classes have already been statically woven. Run the static weaver on the classes before deploying them. For more information, see the following:
<property name="eclipselink.weaving" value="false"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING, "false"); |
true |
eclipselink.weaving.lazy |
Enable or disable the lazy one-to-one (see @OneToOne) and many-to-one (see @ManyToOne) mapping through weaving. The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true or static. The purpose of the eclipselink.weaving.lazy option is to provide more granular control over weaving. For more information, see the following:
<property name="eclipselink.weaving.lazy" value="false"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_LAZY, "false"); |
true |
eclipselink.weaving.changetracking |
Enable or disable the AttributeLevelChangeTracking through weaving. The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true or static. The purpose of the eclipselink.weaving.changetracking option is to provide more granular control over weaving. For more information, see the following:
<property name="eclipselink.weaving.changetracking" value="false"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "false"); |
true |
eclipselink.weaving.fetchgroups |
Enable or disable fetch groups through weaving. The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true or static. The purpose of the eclipselink.weaving.fetchgroups option is to provide more granular control over weaving. For more information, see the following:
<property name="eclipselink.weaving.fetchgroups" value="false"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_FETCHGROUPS, "false"); |
true |
eclipselink.weaving.internal |
Enable or disable internal optimizations through weaving. The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true or static. The purpose of the eclipselink.weaving.internal option is to provide more granular control over weaving. For more information, see Using EclipseLink JPA Weaving.
<property name="eclipselink.weaving.internal" value="false"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_INTERNAL, "false"); |
true |
eclipselink.weaving.eager |
Enable or disable indirection on eager relationships through weaving. (Even one-to-one and many-to-one relations with FetchType.EAGER become effectively "lazy".) The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true or static. The purpose of the eclipselink.weaving.eager option is to provide more granular control over weaving. For more information, see the following:
<property name="eclipselink.weaving.eager" value="true"/>
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_EAGER, "true"); |
false |
eclipselink.session.customizer |
Specify an EclipseLink session customizer class: a Java class that implements the org.eclipse.persistence.config.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.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.config.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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER+".Order", "acme.sessions.MyDescriptorCustomizer"); |
|
eclipselink.validation-only |
Specify whether or not deployment should be for validation only. The following are the valid values:
<property name="eclipselink.validation-only" value="false"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.ECLIPSELINK_VALIDATION_ONLY_PROPERTY, "false"); |
true |
eclipselink.classloader |
Specify the class loader to use for creation of an EntityManagerFactory in the property map passed to the createEntityManagerFactory method.
<property name="eclipselink.classloader" value="MyClassloader"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CLASSLOADER, "MyClassloader"); |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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 use in a persistence.xml file and for the org.eclipse.persistence.config.ProfilerType:
<property name="eclipselink.profiler" value="PerformanceProfiler"/> Example: property Map import org.eclipse.persistence.config.ProfilerType; import org.eclipse.persistence.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.config.ProfilerType; import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.PROFILER, "mypackage.com.MyProfiler"); |
NoProfiler |
eclipselink.persistence.context.reference-mode |
Specify whether or not the Java VM is allowed to manage the number of objects within the persistence context using Java’s weak references. In cases where your application cannot use the EntityManager clear method to clear an extended persistence context, use this setting to enable the VM to remove unreferenced and unchanged objects from the persistence context, resulting in making resources available for other uses. You can set this property either during the EntityManagerFactory createEntityManager(Map) call, or globally in the persistence.xml file. The following are the valid values for the use in a persistence.xml file and for the org.eclipse.persistence.sessions.factories.ReferenceMode:
Using Java, you can configure reference mode through the EclipseLink Session's acquireUnitOfWork(ReferenceMode mode) method. To specify a persistence unit- or session-wide default, use the Session's setDefaultReferenceMode method. For more information, see the following:
<property name="eclipselink.persistence-context.reference-mode" value="FORCE_WEAK"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, ReferenceMode.FORCE_WEAK); |
WEAK |
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 Copy Policy
The copy policy enables EclipseLink to produce exact copies of persistent objects. For more information, see Configuring Copy Policy.
EclipseLink defines the following copy policy annotations:
How to Use the @CopyPolicy Annotation
Use the @CopyPolicy annotation to specify a class that implements the org.eclipse.persistence.descriptors.copying.CopyPolicy interface to set the copy policy on an Entity.
@Target({TYPE}) @Retention(RUNTIME) public @interface CopyPolicy { Class value(); }
You can define the @CopyPolicy annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass
This table lists attributes of the @CopyPolicy annotation.
Attributes of the @CopyPolicy Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
value |
Set this attribute to the Class of the copy policy that you want to apply to your entity's descriptor. |
no default |
required |
This example shows how to use the @CopyPolicy annotation.
Usage of the @CopyPolicy Annotation
@Entity @Table(name="EMPLOYEE") @CopyPolicy(mypackage.MyCopyPolicy.class) public class Employee implements Serializable { ... }
How to Use the @CloneCopyPolicy Annotation
Use the @CloneCopyPolicy annotation to set the clone copy policy (org.eclipse.persistence.descriptors.copying.CloneCopyPolicy) on an Entity.
@Target({TYPE}) @Retention(RUNTIME) public @interface CloneCopyPolicy { Sting method(); Sting workingCopyMethod(); }
The @CloneCopyPolicy must specify one or both of the method or workingCopyMethod attributes based on the following:
- Use the method for the clone whose function is comparison in conjunction with EclipseLink's DeferredChangeDetectionPolicy (see Deferred Change Detection Policy).
- Use the workingCopyMethod to clone objects that will be returned, as they are registered in EclipseLink's transactional mechanism (the unit of work).
You can define the @CloneCopyPolicy annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass
This table lists attributes of the @CloneCopyPolicy annotation.
Attributes of the @CloneCopyPolicy Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
method |
Set this attribute to the String method name that EclipseLink will use to create a clone to enable comparison by EclipseLink's deferred change detection policy) that you want to apply to your entity's descriptor. Note: you have to set either this attribute, or the workingCopyMethod, or both. |
no default |
optional/required |
workingCopyMethod |
Set this attribute to the String method name that EclipseLink will use to create the object returned when registering an Object in an EclipseLink unit of work. Note: you have to set either this attribute, or the method, or both. |
no default |
optional/required |
How to Use the @InstantiationCopyPolicy Annotation
Instantiation copy policy is the default copy policy in EclipseLink. Use the @InstantiationCopyPolicy annotation to override other types of copy policies for an Entity.
@Target({TYPE}) @Retention(RUNTIME) public @interface CloneCopyPolicy { }
You can define the @InstantiationCopyPolicy annotation on the following:
- @Entity (see Section 8.1 "Entity" of the JPA Specification);
- @MappedSuperclass
The @InstantiationCopyPolicy annotation does not have attributes.
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.
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;
- 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:
How to Use the @ReturnInsert Annotation
You can only specify the @ReturnInsert for a @Basic mapping.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface ReturnInsert { boolean returnOnly() default false; }
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.
@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.
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 { OptimisticLockingType type() default VERSION_COLUMN; Column[] selectedColumns() default {}; boolean cascade() default false; }
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 the 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:
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 { String name(); String procedureName(); QueryHint[] hints() default {}; Class resultClass() default void.class; String resultSetMapping() default ""; boolean returnsResultSet() default false; StoredProcedureParameter[] parameters() default {}; }
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 |
parameters |
Set the value of this attribute to an array of @StoredProcedureParameter instances to define arguments to the stored procedure. |
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", parameters={ @StoredProcedureParameter(queryParamater="EMP_ID")} ) public class Employee implements Serializable{ ... }
How to Use the @StoredProcedureParameter Annotation
Use the @StoredProcedureParameter annotation within a @NamedStoredProcedureQuery annotation to define arguments to the stored procedure.
@Target({}) @Retention(RUNTIME) public @interface StoredProcedureParameter { String queryParameter(); Direction direction() default IN; int jdbcType() default -1; String jdbcTypeName() default ""; String name() default ""; Class type() default void.class; }
This table lists attributes of the @StoredProcedureParameter annotation.
Attributes of the @StoredProcedureParameter Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
queryParameter |
Set this attribute to the String query parameter name. |
no default |
required |
direction |
Set the value of this attribute to define the direction(org.eclipse.persistence.annotations.Direction enumerated type) of the stored procedure parameter. The following are valid values for Direction.IN:
|
empty Direction.IN |
optional |
name |
Set this attribute to the String name of the stored procedure parameter. |
"" |
optional |
type |
Set this attribute to the type of Java Class that you want to receive back from the procedure. This depends on the type returned from the procedure. |
void.class |
optional |
jdbcType |
Set this attribute to the int value of JDBC type code. This depends on the type returned from the procedure. |
-1 |
optional |
jdbcTypeName |
Set this attribute to the String value of the JDBC type name. |
"" |
optional |
The Usage of the @NamedStoredProcedureQuery Annotation example shows how to use the @StoredProcedureParameter annotation.
For more information, see the following:
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 { NamedStoredProcedureQuery[] value(); }
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 the @NamedStoredProcedureQuery annotations. |
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 binding1. 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.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).2 The following are the valid values:
<property name="eclipselink.jdbc.native-sql" value="true"/> Example: property Map import org.eclipse.persistence.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 operations2. Set the value of this property into the session at deployment time. The following are the valid values for the use in a persistence.xml file and for the org.eclipse.persistence.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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.OracleJDBC); |
None |
eclipselink.jdbc.cache-statements |
Enable or disable EclipseLink internal statement caching.2 Note: we recommend enabling this functionality if you are using EclipseLink connection pooling. The following are the valid values:
<property name="eclipselink.jdbc.cache-statements" value="false"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_STATEMENTS, "false"); |
false |
eclipselink.jdbc.cache-statements.size |
The number of statements held when using internal statement caching.2 Set the value at the deployment time. 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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, "2"); |
50 |
eclipselink.jdbc.exclusive-connection.is-lazy |
Specify when a write connection is acquired lazily. For more information, see Lazy Connection Acquisition. The following are the valid values:
For more information, see Configuring Connection Policy.
<property name="eclipselink.jdbc.exclusive-connection.is-lazy" value="false"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, "false"); |
true |
eclipselink.jdbc.exclusive-connection.mode |
Specify when EclipseLink should perform reads through a write connection. For more information, see Exclusive Write Connections. You can set this property while creating either an EntityManagerFactory (either in the map passed to the createEntityManagerFactory method, or in the persistence.xml file), or an EntityManager (in the map passed to the createEntityManager method). Note that the latter overrides the former. The following are the valid values for the use in a persistence.xml file and for the org.eclipse.persistence.config.ExclusiveConnectionMode:
For more information, see Configuring Connection Policy.
<property name="eclipselink.jdbc.exclusive-connection.mode" value="Always"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, "Always"); |
Transactional |
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.3
<property name="eclipselink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver"); |
|
eclipselink.jdbc.password |
The password for your JDBC user.3
<property name="eclipselink.jdbc.password" value="tiger"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_PASSWORD, "tiger"); |
|
eclipselink.jdbc.url |
The JDBC connection URL required by your JDBC driver.3
<property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@MYHOST:1521:MYSID"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_URL, "jdbc:oracle:thin:@MYHOST:1521:MYSID"); |
|
eclipselink.jdbc.user |
The user name for your JDBC user.3
<property name="eclipselink.jdbc.url" value="scott"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_USER, "scott"); |
|
1 This property applies when used in a Java SE environment.
2 This property applies when used both in a Java SE and Java EE environment.
3 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).
4 To do this, set the eclipselink.cache.shared.<ENTITY> property for one or more entities to false; Use the eclipselink.cache.shared.default property if you want to use the isolated cache for all entities.
For information about the use of annotations as opposed to persistence unit properties and vice versa, see the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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.
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.1 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.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.1 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.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.1 The following are the valid values:
<property name="eclipselink.jdbc.read-connections.shared" value="true"/> Example: property Map import org.eclipse.persistence.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.1 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.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.1 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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN, "2"); |
5 |
1 This property applies when used in a Java SE environment.
For information about the use of annotations as opposed to persistence unit properties and vice versa, see the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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. Additional information (including examples) is available in How to configure a custom logger in JPA.
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 for the use in the persistence.xml file and for the org.eclipse.persistence.config.PersistenceUnitProperties:
<property name="eclipselink.logging.logger" value="acme.loggers.MyCustomLogger" /> Example: property Map import org.eclipse.persistence.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 use in the persistence.xml file and for the java.util.logging.Level:
<property name="eclipselink.logging.level" value="OFF" /> Example: property Map import java.util.logging.Level; import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_LEVEL, Level.OFF); |
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.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.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.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.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).1 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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.LOGGING_FILE, "C:\myout\"); |
|
1 This property applies when used in a Java SE environment.
For information about the use of annotations as opposed to persistence unit properties and vice versa, see the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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.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.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.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 from the descriptors to the session. These queries include the ones defined using EclipseLink API, descriptor amendment 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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, "false"); |
true |
eclipselink.target-database |
Specify the type of database that your JPA application uses. The following are the valid values for the use in a persistence.xml file and for the org.eclipse.persistence.config.TargetDatabase:
You can also set the value to the fully qualified classname of a subclass of the org.eclipse.persistence.platform.database.DatabasePlatform class.
<property name="eclipselink.target-database" value="Oracle"/> Example: persistence.xml file <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.HSQLPlatform"/> Example: property Map import org.eclipse.persistence.config.TargetDatabase; import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.TARGET_DATABASE, TargetDatabase.Oracle); |
Auto |
eclipselink.target-server |
Specify the type of application server that your JPA application uses. The following are the valid values for the use in the persistence.xml file and the org.eclipse.persistence.config.TargetServer:
<property name="eclipselink.target-server" value="OC4J_10_1_3"/> Example: property Map import org.eclipse.persistence.config.TargetServer; import org.eclipse.persistence.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 the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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 use in a persistence.xml file:
The following are the valid values for the org.eclipse.persistence.config.PersistenceUnitProperties:
If you are using persistence in a Java SE environment and would like to create the DDL files without creating tables, additionally define a Java system property INTERACT_WITH_DB and set its value to false.
<property name="eclipselink.ddl-generation" value="create-tables"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY); |
none or PersistenceUnitProperties.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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.APP_LOCATION, "C:\ddl\"); |
"."+File.separator or <tt>PersistenceUnitProperties.DEFAULT_APP_LOCATION</tt> |
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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql"); |
createDDL.jdbc or PersistenceUnitProperties.DEFAULT_CREATE_JDBC_FILE_NAME |
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.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql"); |
dropDDL.jdbc or PersistenceUnitProperties.DEFAULT_DROP_JDBC_FILE_NAME |
eclipselink.ddl-generation.output-mode |
Use this property to specify the DDL generation target. The following are the valid values for the use in the persistence.xml file:
The following are the valid values for the org.eclipse.persistence.config.PersistenceUnitProperties:
<property name="eclipselink.ddl-generation.output-mode" value="database"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION); |
Container or Java EE mode: database Note: This setting may be overridden by containers with specific EclipseLink support. Please, refer to your container documentation for details. Bootstrap or Java SE mode: both or PersistenceUnitProperties.DDL_BOTH_GENERATION |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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 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 { ChangeTrackingType value() default AUTO; }
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. The following are the valid values for the ChangeTrackingType:
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 eclipselink.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 |
---|---|---|
eclipselink.weaving.changetracking |
Enable or disable the AttributeLevelChangeTracking through weaving. The following are the valid values:
Note: you may set this option only if the eclipselink.weaving option is set to true. The purpose of the eclipselink.weaving.changetracking option is to provide more granular control over weaving. For more information, see the following:
<property name="eclipselink.weaving.changetracking" value="false"/> Example: property Map import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, "false"); |
true |
For information about the relationship between the value attribute of the @ChangeTracking annotation and eclipselink.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 the following:
- What You May Need to Know About Overriding Annotations in JPA
- 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.
What You May Need to Know About the Relationship Between the Change Tracking Annotation and Persistence Unit Property
The following table shows the dependency between the value attribute of the @ChangeTracking annotation and the eclipselink.weaving.changetracking property (see How to Use the Persistence Unit Properties for Change Tracking).
Relationship Between the Change Tracking Annotation and Property
@ChangeTracking(value=) | eclipselink.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 tracking. Deferred change tracking is used. |
DEFERRED |
false |
Do not weave change tracking. Deferred change tracking 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 tracking. Deferred change tracking 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.
All EclipseLink query hints are defined in the QueryHints class in the org.eclipse.persistence.config package.
The EclipseLink query hints include the following:
- eclipselink.cache-usage
- eclipselink.query-type
- eclipselink.jdbc.bind-parameters
- eclipselink.pessimistic-lock
- eclipselink.refresh
- eclipselink.refresh.cascade
- eclipselink.maintain-cache
- eclipselink.batch
- eclipselink.join-fetch
- eclipselink.read-only
- eclipselink.jdbc.timeout
- eclipselink.jdbc.fetch-size
- eclipselink.jdbc.max-rows
- eclipselink.result-collection-type
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.config package, including the following:
- HintValues
- CacheUsage
- PessimisticLock
- 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 QueryHints 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.config.HintValues; import org.eclipse.persistence.config.QueryHints; Customer customer = (Customer)entityMgr.createNamedQuery("findCustomerBySSN"). setParameter("SSN", "123-12-1234"). setHint(QueryHints.BIND_PARAMETERS, HintValues.PERSISTENCE_UNIT_DEFAULT). getSingleResult();
Specifying an EclipseLink JPA Query Hint with @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @Entity @NamedQuery( name="findEmployeeByDept", query="SELECT e FROM Employee e WHERE e.dept=:deptNum", hints=@QueryHint(name=QueryHints.BIND_PARAMETERS, value=HintValues.TRUE) ) public class Employee implements Serializable { ... }
Cache Usage
The eclipselink.cache-usage hint specifies 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.config.CacheUsage:
- DoNotCheckCache – Always go to the database.
- CheckCacheByExactPrimaryKey – If a read-object query contains an expression where the primary key is the only comparison, you can obtain a cache hit if you process the expression against the object in memory
- CheckCacheByPrimaryKey – If a read-object query contains an expression that compares at least the primary key, you can obtain a cache hit if you process the expression against the objects in memory.
- CheckCacheThenDatabase – You can configure any read-object query to check the cache completely before you resort to accessing the database.
- CheckCacheOnly – You can configure any read-all query to check only the parent session cache (shared cache) and return the result from it without accessing the database.
- ConformResultsInUnitOfWork – You can configure any read-object or read-all query within the context of a unit of work to conform the results with the changes to the object made within that unit of work. This includes new objects, deleted objects and changed objects.
For more information, see Using Conforming Queries and Descriptors. - UseEntityDefault – Use the cache configuration as specified by the EclipseLink descriptor API for this entity.
Note: the entity default value is to not check the cache (DoNotCheckCache). The query will access the database and synchronize with the cache. Unless refresh has been set on the query, the cached objects will be returned without being refreshed from the database. EclipseLink does not support the cache usage for native queries or queries that have complex result sets such as returning data or multiple objects.
Default:
CacheUsage.UseEntityDefault
Note: this default is DoNotCheckCache.
For more information, see Configuring Cache Usage for In-Memory Queries.
Example: JPA Query API
import org.eclipse.persistence.config.CacheUsage; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
Example: @QueryHint
import org.eclipse.persistence.config.CacheUsage; import org.eclipse.persistence.config.TargetDatabase; @QueryHint(name=QueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheOnly);
Query Type
The eclipselink.query-type hint specifies 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.config.QueryType:
- Auto – EclipseLink chooses the type of query to use.
- ReadAll – Use the ReadAllQuery type for the query.
- ReadObject – Use the ReadObjectQuery type for the query.
- Report – Use the Report Query type for the query.
Default: QueryType.Auto
Example: JPA Query API
import org.eclipse.persistence.config.QueryType; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadObject);
Example: @QueryHint
import org.eclipse.persistence.config.QueryType; import org.eclipse.persistence.config.TargetDatabase; @QueryHint(name=QueryHints.QUERY_TYPE, value=QueryType.ReadObject);
Bind Parameters
The eclipselink.jdbc.bind-parameters hint controls 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.config.HintValues:
- TRUE – bind all parameters.
- FALSE – do not bind all parameters.
- PERSISTENCE_UNIT_DEFAULT – use the parameter binding setting made in your EclipseLink session's database login, which is true by default.
For more information, see Configuring JDBC Options.
Default: HintValues.PERSISTENCE_UNIT_DEFAULT
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.BIND_PARAMETERS, HintValues.TRUE);
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.TargetDatabase; @QueryHint(name=QueryHints.BIND_PARAMETERS, value=HintValues.TRUE);
Fetch Size
The eclipselink.jdbc.fetch-size hint specifies the number of rows that should be fetched from the database when more rows are needed1
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.
Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
Default: 0
Note: this value indicates that the JDBC driver default will be used.
1 This property is dependent on the JDBC driver support.
Timeout
The eclipselink.jdbc.timeout hint specifies the number of seconds EclipseLink will wait on a query before throwing a DatabaseException1
A value of 0 means EclipseLink will never time-out a query.
Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.
Default: 0
1 This property is dependent on the JDBC driver support.
Pessimistic Lock
The eclipselink.pessimistic-lock hint controls whether or not pessimistic locking is used.
The following are the valid values for the org.eclipse.persistence.config.PessimisticLock:
- NoLock – pessimistic locking is not used.
- Lock – EclipseLink issues a SELECT .... FOR UPDATE.
- LockNoWait – EclipseLink issues a SELECT .... FOR UPDATE NO WAIT.
Default: NoLock
Example: JPA Query API
import org.eclipse.persistence.config.PessimisticLock; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait);
Example: @QueryHint
import org.eclipse.persistence.config.PessimisticLock; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.PESSIMISTIC_LOCK, value=PessimisticLock.LockNoWait);
Batch
The eclipselink.batch hint supplies 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
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint("eclipselink.batch", "e.address");
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.BATCH, value="e.address");
Join Fetch
The eclipselink.join-fetch hint allows 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.
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint("eclipselink.join-fetch", "e.address");
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.FETCH, value="e.address");
Refresh
The eclipselink.refresh hint controls 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.config.HintValues:
- TRUE – refresh cache.
- FALSE – do not refresh cache.
Default: FALSE
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.REFRESH, HintValues.TRUE);
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.REFRESH, value=HintValues.TRUE);
Maintain Cache
The eclipselink.maintain-cache hint controls whether or not query results are cached in the session cache and provides a way to query the current database contents without affecting the current persistence context. It configures the query to return unmanaged instances so any updates to entities queried using this hint would have to be merged into the persistence context.
The following are the valid values for the org.eclipse.persistence.config.HintValues:
- TRUE – maintain cache.
- FALSE – do not maintain cache.
Default: FALSE
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE);
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.MAINTAIN_CACHE, value=HintValues.FALSE);
Read Only
The eclipselink.read-only hint retrieves 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.config.HintValues:
- TRUE – retrieve read-only results back from the query;
- FALSE – do not retrieve read-only results back from the query.
Default: FALSE
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint(QueryHints.READ_ONLY, HintValues.TRUE);
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.READ_ONLY, value=HintValues.TRUE);
Result Collection Type
The eclipselink.result-collection-type hint configures 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.
Default:java.util.Vector
Example: JPA Query API
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; query.setHint("eclipselink.result-collection-type", java.util.ArrayList.class);
Example: @QueryHint
import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; @QueryHint(name=QueryHints.RESULT_COLLECTION_TYPE, value="java.util.ArrayList");
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.
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.
Weaving can be performed either dynamically at runtime, when Entities are loaded, or statically at compile time by post-processing the Entity .class files. By default, EclipseLink uses dynamic weaving whenever possible. This includes inside an Java EE 5/6 application server and in Java SE when the EclipseLink agent is configured. Dynamic weaving is recommended as it is easy to configure and does not require any changes to a project's build process.
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
- Modify your application JVM command line to include the following:
-javaagent:eclipselink.jar
- Ensure that the eclipselink.jar is in your application classpath.
- Package 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.
Prior to weaving, your persistence unit should be set-up in a way that is understood by eclipselink. There are two basic configurations:
1. A jar file - setup as specified in the JPA specification
- classes stored at the base in directories based on their package structure
- a META-INF directory containing your persistence.xml. Note: Using the persistenceunitinfo setting below, you can avoid this requirement
e.g. mypersistenceunit.jar could contain
- mypackage/MyEntity1.class
- mypackage/MyEntity2.class
- mypackage2/MyEntity3.class
- META-INF/persistence.xml
2. An exploded directory structure
- classes stored at the base in directories based on their package structure
- a META-INF directory containing your persistence.xml. Note: Using the persistenceunitinfo setting below, you can avoid this requirement
e.g. If your base directory was c:/classes, the exploded directory structure would look as follows:
- c:/classes/mypackage/MyEntity1.class
- c:/classes/mypackage/MyEntity2.class
- c:/classes/mypackage2/MyEntity3.class
- c:/classes/META-INF/persistence.xml
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 table lists 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.jpa.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 a META-INF directory at 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. Note: persistence.xml should be put in a directory called META-INF at this location
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 table lists the attributes of this task.
- Use the command line as follows:
java org.eclipse.persistence.tools.weaving.jpa.StaticWeave [arguments] <source> <target>
The following example shows how to use the StaticWeave class on Windows systems. The EclipseLink StaticWeave Class Command Line Arguments table lists the arguments of this class.
Executing StaticWeave on the Command Linejava org.eclipse.persistence.tools.weaving.jpa.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 at the same location as the source (see -classpath) Note: EclipseLink will look in a META-INF directory at that location for persistence.xml.
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 eclipselink.weaving extension set to static, as this example shows:
Setting eclipselink.weaving in the persistence.xml File<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="eclipselink.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:
- eclipselink.weaving – disables all weaving;
- eclipselink.weaving.lazy – disables weaving for lazy loading (indirection);
- eclipselink.weaving.changetracking – disables weaving for change tracking;
- eclipselink.weaving.fetchgroups – disables weaving for fetch groups.
- eclipselink.weaving.internal – disables weaving for internal optimization.
- eclipselink.weaving.eager – disables weaving for indirection on eager relationships.
Disabling Weaving for Change Tracking in the persistence.xml File<persistence> <persistence-unit name="HumanResources"> <class>com.acme.Employee</class> ... <properties> <property name="eclipselink.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="eclipselink.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 or many-to-one 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 or many-to-one 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 eclipselink-orm.xml File
The eclipselink-orm.xml file is the EclipseLink native metadata XML file. It can be used to override the JPA configurations defined in the JPA orm.xml file. This exclipselink-orm.xml file provides access to the the advanced features provided by the EclipseLink XSD (http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_1_0.xsd).
See this page for more information and examples.
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.
Note: that EclipseLink does not provide a mechanism for encrypting the password in the persistence.xml file. (see Avoiding Cleartext Passwords) |
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, as the 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.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.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.
Allowing Zero Value Primary Keys
By default, EclipseLink interprets zero as null for primitive types that cannot be null (such as int and long) causing zero to be an invalid value for primary keys. You can modify this setting by using the allow-zero-id property in the persistence.xml file. Valid values are:
- true – EclipseLink interprets zero values as zero. This permits primary keys to use a value of zero.
- false (default) – EclipseLink interprets zero as null.
Avoiding Cleartext Passwords
EclipseLink does not support storing encrypted passwords in the persistence.xml file. For a Java EE application, you do not need to specify your password in the persistence.xml file. Instead, you can specify a data-source, as shown in the Java EE example. This datasource is specified on the application server, and can encrypt the your password with its own mechanism.
For a Java SE application, you should avoid putting the password in the persistence.xml file. Instead, add the password to the properties, as shown in the Setting the password in code example. Setting the password in code allows for the password to be retrieved from any location, including a protected source.
Setting the password in code
Map properties = new HashMap(); properties.put(PersistenceUnitProperties.JDBC_PASSWORD, "tiger"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("default", properties);