Notice: This Wiki is now read only and edits are no longer possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.
EclipseLink/Features/JPA Extensions
Contents
- 1 Using TopLink JPA Extensions
- 1.1 Using TopLink JPA Extensions for Mapping
- 1.2 Using TopLink JPA Converters
- 1.3 Using TopLink JPA Extensions for Entity Caching
- 1.4 Using TopLink JPA Extensions for Customization
- 1.5 Using TopLink JPA Extensions for Returning Policy
- 1.6 Using TopLink JPA Extensions for Optimistic Locking
- 1.7 Using TopLink JPA Extensions for Stored Procedure Query
- 1.8 Using TopLink JPA Extensions for JDBC
- 1.9 Using TopLink JPA Extensions for Logging
- 1.10 Using TopLink JPA Extensions for Session, Target Database and Target Application Server
- 1.11 Using TopLink JPA Extensions for Schema Generation
- 1.12 Using TopLink JPA Extensions for Tracking Changes
- 1.13 Using TopLink JPA Query Customization Extensions
- 1.13.1 How to Use TopLink JPA Query Hints
- 1.13.2 How to Use TopLink Query API in JPA Queries
- 1.13.2.1 Creating a JPA Query Using the TopLink Expressions Framework
- 1.13.2.2 Creating a JPA Query Using a TopLink DatabaseQuery
- 1.13.2.3 Creating a JPA Query Using a TopLink Call Object
- 1.13.2.4 Using Named Parameters in a Native Query
- 1.13.2.5 Using Java Persistence Query Language Positional Parameters in a Native Query
- 1.13.2.6 Using JDBC-Style Positional Parameters in a Native Query
- 1.14 Using TopLink JPA Lazy Loading
- 1.14.1 How to Configure Dynamic Weaving
- 1.14.2 How to Configure Static Weaving Using the Persistence Unit Property
- 1.14.3 How to Configure Static Weaving Using the StaticWeave Class on the Command Line
- 1.14.4 How to Use Static Weaving with the weave Ant Task
- 1.14.5 What You May Need to Know About Weaving
- 1.15 What You May Need to Know About Overriding Annotations
Using TopLink JPA Extensions
Version: 5/18/2007
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.
TopLink JPA provides extensions to what is defined in the JPA specification. These extensions come in persistence unit properties, query hints, annotations, TopLink own XML metadata, and custom API.
This document explains where and how you use the extensions to customize JPA behavior to meet your application requirements.
Using TopLink JPA Extensions for Mapping
TopLink defines the following mapping metadata annotations (in addition to JPA-defined ones):
-
@BasicMap
(see <a href="#BABJCFGC">"How to Use the @BasicMap Annotation"</a>) -
@BasicCollection
(see <a href="#BABDCAFF">"How to Use the @BasicCollection Annotation"</a>) -
@CollectionTable
(see <a href="#BABFHAHH">"How to Use the @CollectionTable Annotation"</a>) -
@PrivateOwned
(see <a href="#BABGGFIB">"How to Use the @PrivateOwned Annotation"</a>) -
@JoinFetch
(see <a href="#CACCFACF">"How to Use the @JoinFetch Annotation"</a>)
TopLink persistence provider searches mapping annotations in the following order:
-
@BasicCollection
-
@BasicMap
-
@EmbeddedId
-
@Embedded
-
@ManyToMany
-
@ManyToOne
-
@OneToMany
-
@OneToOne
TopLink persistence provider applies the first annotation that it finds; it ignores other mapping annotations, if specified. In most cases, TopLink does not log warnings or throw exceptions.
If TopLink 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 (see Section 9.1.18 "Basic Annotation" of the JPA specification)).
<a id="BABJCFGC" name="BABJCFGC"></a>
How to Use the @BasicMap Annotation
You can use the @BasicMap
annotation to map an oracle.toplink.mappings.DirectMapMapping
, which stores a collection of key-value pairs of simple types, such as String
, Number
, Date
, and so on, in a single table. The table must store the value and the foreign key to the source object.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface BasicMap { ... }
Use the @BasicMap
annotation in conjunction with a @CollectionTable
annotation (see <a href="#BABFHAHH">"How to Use the @CollectionTable Annotation"</a>).
<a href="#BABHHCFB">Table 1-1</a> lists attributes of the @BasicMap
annotation.
Table 1-1 Attributes of the @BasicMap Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
|
optional |
|
Set this attribute to the name of the data column ( |
no default |
required |
|
Set this attribute to the key converter ( |
|
optional |
|
Set this attribute to the name of the value column ( |
Note: TopLink persistence provider sets the default to the name of the field or property. |
optional |
|
Set this attribute to the value converter ( |
|
optional |
Note: If you specify@BasicMap on an attribute of type Collection , TopLink will throw an exception. |
<a href="#BABFDCCJ">Example 1-1</a> shows how to use the @BasicMap
annotation to specify Employee
field licenses
.
Example 1-1 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="EAGER", keyColumn=@Column(name="LICENSE"), keyConverter=@Convert("licenseConverter"), valueColumn=@Column(name="STATUS")), valueConverter=@Convert("Integer2String") ) @ObjectConverter( name="licenseConverter", conversionValues={ @ConversionValue(dataValue="AL", objectValue="Alcohol License"), @ConversionValue(dataValue="FD", objectValue="Food License"), @ConversionValue(dataValue="SM", objectValue="Smoking License"), @ConversionValue(dataValue="SL", objectValue="Site Licence")} ) @CollectionTable ( name="LICENSE", primaryKeyJoinColumns={@PrimaryKeyJoinColumn(name="REST_ID")} ) public Map<String> getLicenses() { return licenses; } ... }
<a id="BABDCAFF" name="BABDCAFF"></a>
How to Use the @BasicCollection Annotation
You can use the @BasicCollection
annotation to map an oracle.toplink.mappings.DirectCollectionMapping
, which stores a collection of simple types, such as String
, Number
, Date
, and so on, in a single table. The table must store the value and the foreign key to the source object.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface BasicCollection { ... }
Use the @BasicCollection
annotation in conjunction with a @CollectionTable
annotation (see <a href="#BABFHAHH">"How to Use the @CollectionTable Annotation"</a>). You can also use it in conjunction with @Convert
(see <a href="#BABCHBGG">"How to Use the @Convert Annotation"</a>) to modify the data value(s) during reading and writing of the collection.
<a href="#BABEIFAC">Table 1-2</a> lists attributes of the @BasicCollection
annotation.
Table 1-2 Attributes of the @BasicCollection Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
The |
|
optional |
|
The name of the value column ( |
Note: TopLink 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 , TopLink will throw an exception. |
<a href="#BABEBJDI">Example 1-2</a> shows how to use the @BasicCollection
annotation to specify Employee
field responsibilities
.
Example 1-2 Usage of the @BasicCollection Annotation
@Entity public class Employee implements Serializable{ ... @BasicCollection ( fetch="EAGER", valueColumn=@Column(name="DESCRIPTION") ) @CollectionTable ( name="RESPONS", primaryKeyJoinColumns= {@PrimaryKeyJoinColumn(name="EMPLOYEE_ID", referencedColumnName="EMP_ID")} ) public Collection getResponsibilities() { return responsibilities; } ... }
<a id="BABFHAHH" name="BABFHAHH"></a>
How to Use the @CollectionTable Annotation
You can use the @CollectionTable
annotation in conjunction with a @BasicCollection
annotation (see <a href="#BABDCAFF">"How to Use the @BasicCollection Annotation"</a>) or the @BasicMap
annotation (see <a href="#BABJCFGC">"How to Use the @BasicMap Annotation"</a>). If you do not specify the @CollectionTable
, TopLink persistence provider will use the defaults.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface CollectionTable { ... }
<a href="#BABFJECG">Table 1-3</a> lists attributes of the @CollectionTable
annotation.
Table 1-3 Attributes of the @CollectionTable Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
empty Note: TopLink persistence provider applies the following concatenated |
optional |
|
Set this attribute to the |
empty Note: TopLink persistence provider sets the default to the persistence unit's default catalog. |
optional |
|
Set this attribute to the |
empty Note: TopLink persistence provider sets the default to the persistence unit's default schema. |
optional |
|
Set this attribute to an array of
If the source entity uses a composite primary key and you failed to specify the primary key join columns, TopLink will throw an exception. |
empty |
optional |
|
Set this attribute to an array of |
empty |
optional |
<a href="#CJAGDAFA">Example 1-3</a> shows how to use the @CollectionTable
annotation to specify Employee
field responsibilities
.
Example 1-3 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; } ... }
<a id="BABGGFIB" name="BABGGFIB"></a>
How to Use the @PrivateOwned Annotation
Use the @PrivateOwned
annotation in conjunction with a @OneToOne
annotation (see Section 9.1.23 "OneToOne Annotation" of the JPA specification), or a @OneToMany
annotation (see Section 9.1.24 "OneToMany Annotation" of the JPA specification).
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface PrivateOwned { ... }
The @PrivateOwned
annotation does not have attributes.
<a href="#BABFADHG">Example 1-4</a> shows how to use the @PrivateOwned
annotation to specify Employee
field managedEmployees
.
Example 1-4 Usage of the @PrivateOwned Annotation
@Entity public class Employee implements Serializable { ... @OneToMany(cascade=ALL, mappedBy="owner") @PrivateOwned public Collection getPhoneNumbers() { return phoneNumbers; } ... }
What You May Need to Know About Private Ownership of Objects
When the referenced object is privately owned the referenced child object cannot exist without the parent object.
When you tell TopLink 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:
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/descun.htm#CHECICGH">Optimistic Version Locking Policies and Cascading</a>
-
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;
-
Section 9.1.23 "OneToOne Annotation" of the JPA specification;
-
Section 9.1.22 "ManyToOne Annotation" of the JPA specification;
-
Section 9.1.24 "OneToMany Annotation" of the JPA specification;
-
-
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 "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowbas.htm#i1134011">Using the privateOwnedRelationship Attribute</a>".
<a id="CACCFACF" name="CACCFACF"></a>
How to Use the @JoinFetch Annotation
You can specify the @JoinFetch
annotation for the following mappings:
-
@OneToOne
(see Section 9.1.23 "OneToOne Annotation" of the JPA specification); -
@OneToMany
(see Section 9.1.24 "OneToMany Annotation" of the JPA specification); -
@ManyToOne
(see Section 9.1.22 "ManyToOne Annotation" of the JPA specification); -
@ManyToMany
(see Section 9.1.26 "ManyToMany Annotation" of the JPA specification); -
@BasicCollection
(see <a href="#BABDCAFF">"How to Use the @BasicCollection Annotation"</a>); -
@BasicMap
(see <a href="#BABJCFGC">"How to Use the @BasicMap Annotation"</a>).
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface JoinFetch { ... }
Using the @JoinFetch
annotation, you can enable the joining and reading of the related objects in the same query as the source object.
Note: Oracle recommends setting join fetching at the query level, as not all queries require joining. For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qrybas.htm#a1158158">Using Join Reading</a>". |
Alternatively, you can use batch reading, especially for collection relationships. For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qrybas.htm#i1165217">Using Batch Reading</a>".
<a href="#BABFHHEH">Table 1-4</a> lists attributes of the @JoinFetch
annotation.
Table 1-4 Attributes of the @JoinFetch Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the The following are the valid values for the
For more information, see the following:
|
|
optional |
</div> <a id="BABDFDIG" name="BABDFDIG"></a>
Using TopLink JPA Converters
TopLink defines the following converter annotations (in addition to JPA-defined ones):
-
@Converter
(see <a href="#BABDBCIA">"How to Use the @Converter Annotation"</a>) -
@TypeConverter
(see <a href="#BABHEDEE">"How to Use the @TypeConverter Annotation"</a>) -
@ObjectTypeConverter
(see <a href="#BABGCAEA">"How to Use the @ObjectTypeConverter Annotation"</a>) -
@Convert
(see <a href="#BABCHBGG">"How to Use the @Convert Annotation"</a>)
TopLink persistence provider searches the converter annotations in the following order:
-
@Converter
(see <a href="#BABDBCIA">"How to Use the @Converter Annotation"</a>) -
@Enumerated
(see Section 9.1.21 "Enumerated Annotation" of the JPA specification) -
@Lob
(see Section 9.1.19 "Lob Annotation" of the JPA specification) -
@Temporal
(see Section 9.1.20 "Temporal Annotation" of the JPA specification) -
Serialized (automatic)
You can define converters at the class, field and property level. You can specify TopLink converters on the following classes:
-
@Entity
(see Section 8.1 "Entity" of the JPA specification); -
@MappedSuperclass
(see Section 9.1.36 "MappedSuperclass Annotation" of the JPA specification); -
@Embeddable
(see Section 9.1.34 "Embeddable Annotation" of the JPA specification).
TopLink supports the use of converters with the following:
-
@Basic
(see Section 9.1.18 "Basic Annotation" of the JPA specification) -
@BasicMap
(see <a href="#BABJCFGC">"How to Use the @BasicMap Annotation"</a>) -
@BasicCollection
(see <a href="#BABDCAFF">"How to Use the @BasicCollection Annotation"</a>)
If you specify a converter with any other type of mapping annotation, TopLink will throw an exception.
<a id="BABDBCIA" name="BABDBCIA"></a>
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 { ... }
<a href="#BABJCFIG">Table 1-5</a> lists attributes of the @Converter
annotation.
Table 1-5 Attributes of the @Converter Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
no default |
required |
|
Set this attribute to the |
no default |
required |
<a href="#BABFHCDB">Example 1-5</a> shows how to use the @Converter
annotation to specify Employee
field gender
.
Example 1-5 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; } ... }
<a id="BABHEDEE" name="BABHEDEE"></a>
How to Use the @TypeConverter Annotation
The @TypeConverter
is a TopLink-specific annotation. You can use it to specify a TopLink oracle.toplink.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 { ... }
<a href="#BABEAFDC">Table 1-6</a> lists attributes of the @TypeConverter
annotation.
Table 1-6 Attributes of the @TypeConverter Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
no default |
required |
|
Set this attribute to the type stored in the database. |
Note: The default is inferred from the type of the persistence field or property. |
optional |
|
Set the value of this attribute to the type stored on the entity. |
Note: The default is inferred from the type of the persistence field or property. |
optional |
<a href="#BABECICJ">Example 1-6</a> shows how to use the @TypeConverter
annotation to convert the Double
value stored in the database to a Float
value stored in the entity.
Example 1-6 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; } ... }
<a id="BABGCAEA" name="BABGCAEA"></a>
How to Use the @ObjectTypeConverter Annotation
You can use the @ObjectTypeConverter
annotation to specify a TopLink oracle.toplink.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 { ... }
<a href="#BABFCGJF">Table 1-7</a> lists attributes of the @ObjectTypeConverter
annotation.
Table 1-7 Attributes of the @ObjectTypeConverter Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
no default |
required |
|
Set this attribute to the type stored in the database. |
Note: The default is inferred from the type of the persistence field or property. |
optional |
|
Set the value of this attribute to the type stored on the entity. |
Note: The default is inferred from the type of the persistence field or property. |
optional |
|
Set the value of this attribute to the array of conversion values (instances of |
no default |
required |
|
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 |
optional |
<a href="#BABJEBJA">Example 1-7</a> shows how to use the @ObjectTypeConverter
annotation to specify the Employee
field gender
.
Example 1-7 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; } ... }
<a id="BABCHBGG" name="BABCHBGG"></a>
How to Use the @Convert Annotation
The @Convert
annotation specifies that a named converter should be used with the corresponding mapped attribute.
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Convert { ... }
The @Convert
has the following reserved names:
-
serialized
–places theoracle.toplink.mappings.converters.SerializedObjectConverter
on the associated mapping. -
none
–does not place a converter on the associated mapping.
<a href="#BABBJEIF">Table 1-8</a> lists attributes of the @Convert
annotation.
Table 1-8 Attributes of the @Convert Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
|
optional |
<a href="#BABHHCCH">Example 1-8</a> shows how to use the @Convert
annotation to define the Employee
field gender
.
Example 1-8 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; } ... }
<a id="BABGDJBC" name="BABGDJBC"></a>
Using TopLink JPA Extensions for Entity Caching
The TopLink cache is an in-memory repository that stores recently read or written objects based on class and primary key values. TopLink 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 TopLink cache and its default behavior, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/cachun.htm#CHEJAEBH">Understanding the Cache</a>".
TopLink defines the following entity caching annotations:
-
@Cache
(see <a href="#BABFCJJB">"How to Use the @Cache Annotation"</a>) -
@TimeOfDay
(see <a href="#BABCIHBD">"How to Use the @TimeOfDay Annotation"</a>)
TopLink also provides a number of persistence unit properties that you can specify to configure the TopLink cache (see <a href="#CACCFEAG">"How to Use the Persistence Unit Properties for Caching"</a>). These properties may compliment or provide an alternative to the usage of annotations. For more information, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="BABFCJJB" name="BABFCJJB"></a>
How to Use the @Cache Annotation
TopLink uses identity maps to cache objects in order to enhance performance, as well as maintain object identity. You can control the cache and its behavior by decorating your entity classes with the @Cache
annotation.
@Target({TYPE}) @Retention(RUNTIME) public @interface Cache { ... }
You may define the @Cache
annotation on the following:
-
@Entity
(see Section 8.1 "Entity" of the JPA specification); -
@MappedSuperclass
(see Section 9.1.36 "MappedSuperclass Annotation" of the JPA specification); -
the root of the inheritance hierarchy (if applicable).
<tbody>
Note:
If you define the@Cache
annotation on an inheritance subclass, the annotation will be ignored.
<a href="#BABHBIJE">Table 1-9</a> lists attributes of the @Cache
annotation.
Table 1-9 Attributes of the @Cache Annotation
Attribute | Description | Default | Required or Optional | Override with Persistence Unit Property |
---|---|---|---|---|
<a id="CACDJFCF" name="CACDJFCF"></a> |
Set this attribute to the type ( The following are the valid values for the
|
|
optional |
|
|
Set this attribute to a |
|
optional |
|
|
Set this attribute to the |
-1 (no expiry) |
optional |
|
|
Set this attribute to a specific time of day ( |
|
optional |
|
|
Set this attribute to a |
|
optional |
|
|
Set this attribute to a Note: this option only applies if one of the other refreshing options, such as Note: a version field is necessary to apply this feature. For more information, see the following:
|
|
optional |
|
|
Set this attribute to a |
|
optional |
|
|
Set this attribute to the cache coordination mode ( The following are the valid values for the
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/cachun.htm#CHEDFBFB">Understanding Cache Coordination</a>". |
|
optional |
Note: If you define the@Cache annotation on @Embeddable , TopLink will throw an exception. |
<a href="#BABIHGBG">Example 1-9</a> shows how to achieve the desired behavior of the TopLink cache by defining the attributes of the @Cache
annotation.
Example 1-9 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 { ... }
<a id="CJAEHCDC" name="CJAEHCDC"></a>
What You May Need to Know About Version Fields
By default, TopLink persistence provider assumes that the application is responsible for data consistency.
Use the @Version
annotation (see Section 9.1.17 "Version Annotation" of theJPA specification) 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.
<a id="CACCFEAG" name="CACCFEAG"></a>
How to Use the Persistence Unit Properties for Caching
<a href="#CJAFFDEG">Table 1-10</a> lists the persistence unit properties that you can define in a persistence.xml
file to configure the TopLink cache.
For more information, see the following:
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/cachun.htm#CHEJAEBH">Understanding the TopLink Cache</a>
-
<a href="#CJAFAHEJ">What You May Need to Know About Overriding Annotations</a>
Table 1-10 TopLink JPA Properties for Caching
Property | Usage | Default |
---|---|---|
<a id="toplink.cache.type.default" name="toplink.cache.type.default"></a>
<a id="CACCAEFH" name="CACCAEFH"></a> |
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, TopLink 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 The following are the valid values for the
Note: the values are case-sensitive. Note: using this property, you can override the Example: <property name="toplink.cache.type.default" value="Full"/> Example: property import oracle.toplink.config.CacheType; import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_TYPE_DEFAULT, CacheType.Full); |
|
<a id="toplink.cache.size.default" name="toplink.cache.size.default"></a>
|
The default maximum number of objects allowed in a TopLink cache. Valid values: Example: <property name="toplink.cache.size.default" value="5000"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_SIZE_DEFAULT, 5000); |
1000 |
<a id="toplink.cache.shared.default" name="toplink.cache.shared.default"></a>
|
The default for whether or not the TopLink session cache is shared by multiple client sessions. The following are the valid values:
Example: <property name="toplink.cache.shared.default" value="true"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_SHARED_DEFAULT, "true"); |
|
<a id="toplink.cache.type.ENTITY" name="toplink.cache.type.ENTITY"></a>
<a id="CACGFGJE" name="CACGFGJE"></a> |
The type of session cache for the JPA entity named For more information on entity names, see Section 8.1 "Entity" of the JPA specification. The following are the valid values for the
Note: using this property, you can override the Example: <property name="toplink.cache.type.Order" value="Full"/> Example: property import oracle.toplink.config.CacheType; import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.CACHE_TYPE+".Order", CacheType.Full); |
|
<a id="toplink.cache.size.ENTITY" name="toplink.cache.size.ENTITY"></a>
|
The maximum number of JPA entities of the type denoted by JPA entity name For more information on entity names, see Section 8.1 "Entity" of the JPA specification. Valid values: Example: <property name="toplink.cache.size.Order" value="5000"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_SIZE+".Order", 1000); |
1000 |
<a id="toplink.cache.shared.ENTITY" name="toplink.cache.shared.ENTITY"></a>
|
Whether or not the TopLink session cache is shared by multiple client sessions for JPA entities of the type denoted by JPA entity name For more information on entity names, see Section 8.1 "Entity" of the JPA specification. The following are the valid values:
Example: <property name="toplink.cache.shared.Order" value="true"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_SHARED+".Order", "true"); |
|
<a id="BABCIHBD" name="BABCIHBD"></a>
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 { ... }
<a href="#BABEJDEB">Table 1-11</a> lists attributes of the @TimeOfDay
annotation.
Table 1-11 Attributes of the @TimeOfDay Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
0 |
optional |
|
Set this attribute to the |
0 |
optional |
|
Set this attribute to the |
0 |
optional |
|
Set this attribute to the |
0 |
optional |
<a id="BABHBEDD" name="BABHBEDD"></a>
Using TopLink JPA Extensions for Customization
TopLink defines the following descriptor customizer annotations:
-
@Customizer
(see <a href="#BABHIJJA">"How to Use the @Customizer Annotation"</a>) -
@ReadOnly
(see <a href="#BABBAAHB">"How to Use the @ReadOnly Annotation"</a>)
TopLink also provides a number of persistence unit properties that you can specify to configure TopLink customization and validation (see <a href="#CACDAFAG">"How to Use the Persistence Unit Properties for Customization and Validation"</a>). 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 <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>. |
<a id="BABHIJJA" name="BABHIJJA"></a>
How to Use the @Customizer Annotation
Use the @Customizer
annotation to specify a class that implements the oracle.toplink.tools.sessionconfiguration.DescriptorCustomizer
interface and that is to be run against a class' descriptor after all metadata processing has been completed. See <a href="#CJAIHBBG">toplink.descriptor.customizer.<ENTITY></a> for more information.
@Target({TYPE}) @Retention(RUNTIME) public @interface Customizer { ... }
You can define the @Customizer
annotation on the following:
-
@Entity
(see Section 8.1 "Entity" of the JPA specification); -
@MappedSuperclass
(see Section 9.1.36 "MappedSuperclass Annotation" of the JPA specification); -
@Embeddable
(see Section 9.1.34 "Embeddable Annotation" of the JPA specification).
Note: A@Customizer is not inherited from its parent classes. |
<a href="#BABFBIEA">Table 1-12</a> lists attributes of the @Customizer
annotation.
Table 1-12 Attributes of the @Customizer Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
no default |
required |
<a href="#BABIGIAH">Example 1-10</a> shows how to use the @Customizer
annotation.
Example 1-10 Usage of the @Customizer Annotation
@Entity @Table(name="EMPLOYEE") @Customizer(mypackage.MyCustomizer.class) public class Employee implements Serializable { ... }
<a id="CACDAFAG" name="CACDAFAG"></a>
How to Use the Persistence Unit Properties for Customization and Validation
<a href="#CJADHEEB">Table 1-13</a> lists the persistence unit properties that you can define in a persistence.xml
file to configure TopLink customization and validation.
Table 1-13 TopLink JPA Persistence Unit Properties for Customization and Validation
Property | Usage | Default |
---|---|---|
<a id="toplink.orm.throw.exceptions" name="toplink.orm.throw.exceptions"></a>
|
Specify whether or not TopLink JPA should throw an exception or log a warning when it encounters a problem with any of the files listed in a The following are the valid values:
Example: <property name="oracle.orm.throw.exceptions" value="false"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.TOPLINK_ORM_THROW_EXCEPTIONS, "false"); |
|
<a id="toplink.weaving" name="toplink.weaving"></a>
<a id="CJAFECEI" name="CJAFECEI"></a> |
Control whether or not the weaving of the entity classes is performed. Weaving is required in order to use lazy fetching of The following are the valid values:
For more information, including the option of using the TopLink JPA Example: <property name="toplink.weaving" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.WEAVING, "false"); |
|
|
Enable or disable the lazy one-to-one (see Section 9.1.23 "OneToOne Annotation" of the JPA specification) mapping through weaving. The following are the valid values:
Note: you may set this option only if the <a href="#CJAFECEI">toplink.weaving</a> option is set to For more information, see <a href="#CACEDCAF">"Using TopLink JPA Lazy Loading"</a>. Example: <property name="toplink.weaving.lazy" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.WEAVING_LAZY, "false"); |
|
|
Enable or disable the The following are the valid values:
Note: you may set this option only if the <a href="#CJAFECEI">toplink.weaving</a> option is set to For more information, see <a href="#CACEDCAF">"Using TopLink JPA Lazy Loading"</a>. Example: <property name="toplink.weaving.changetracking" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.WEAVING_CHANGE_TRACKING, "false"); |
|
<a id="toplink.session.customizer" name="toplink.session.customizer"></a>
|
Specify a TopLink session customizer class: a Java class that implements the For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#CACGEBJF">Session Customization</a>". Valid values: class name of a Example: <property name="toplink.session.customizer" value="acme.sessions.MySessionCustomizer"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.SESSION_CUSTOMIZER, "acme.sessions.MySessionCustomizer"); |
|
<a id="toplink.descriptor.customizer.ENTITY" name="toplink.descriptor.customizer.ENTITY"></a>
<a id="CJAIHBBG" name="CJAIHBBG"></a> |
Specify a TopLink descriptor customizer class–a Java class that implements the For more information on entity names, see Section 8.1 "Entity" of the JPA specification For more information on TopLink descriptors, see the following:
Note: TopLink does not support multiple descriptor customizers. Valid values: class name of a Example: <property name="toplink.descriptor.customizer.Order" value="acme.sessions.MyDescriptorCustomizer"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.DESCRIPTOR_CUSTOMIZER+".Order", "acme.sessions.MyDescriptorCustomizer"); |
<a id="BABBAAHB" name="BABBAAHB"></a>
How to Use the @ReadOnly Annotation
Use the @ReadOnly
annotation to specify that a class is read-only (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowadv.htm#CACCDEFJ">Read-Only Classes</a>").
Note: Any changes made within a managed instance in a transaction or to a detached instance and merged will have no effect in the context of a read-only entity class. |
@Target({TYPE}) @Retention(RUNTIME) public @interface ReadOnly { ... }
You can define the @ReadOnly
annotation on the following:
-
@Entity
(see Section 8.1 "Entity" of the JPA specification); -
@MappedSuperclass
(see Section 9.1.36 "MappedSuperclass Annotation" of the JPA specification); -
the root of the inheritance hierarchy (if applicable).
The @ReadOnly
annotation does not have attributes.
<a href="#BABGIGFG">Example 1-11</a> shows how to use the @ReadOnly
annotation.
Example 1-11 Usage of the @ReadOnly Annotation
@Entity @ReadOnly public class Employee implements Serializable { ... }
<a id="BABDDFGA" name="BABDDFGA"></a>
Using TopLink 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 "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/descfg.htm#CHDHCCIG">Configuring Returning Policy</a>".
TopLink defines the following returning policy annotations:
-
@ReturnInsert
(see <a href="#BABEACGB">"How to Use the @ReturnInsert Annotation"</a>) -
@ReturnUpdate
(see <a href="#BABFFGJA">"How to Use the @ReturnUpdate Annotation"</a>)
<a id="BABEACGB" name="BABEACGB"></a>
How to Use the @ReturnInsert Annotation
You can only specify the @ReturnInsert
for a @Basic
mapping (see Section 9.1.18 "Basic Annotation" of the JPA specification).
@Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface ReturnInsert { ... }
<a href="#BABIAAEG">Table 1-14</a> lists attributes of the @ReturnInsert
annotation.
Table 1-14 Attributes of the @ReturnInsert Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the |
|
optional |
<a href="#BABBBHIH">Example 1-12</a> shows how to use the @ReturnInsert
annotation without specifying the value for the returnOnly
argument, therefore accepting the default value of false
. <a href="#BABEHAHA">Example 1-13</a> shows how to set the value of the returnOnly
argument to true
.
Example 1-12 Usage of the @ReturnInsert Annotation Without Arguments
@ReturnInsert public String getFirstName() { return firstName; }
Example 1-13 Usage of the @ReturnInsert Annotation with Arguments
@ReturnInsert(returnOnly=true) public String getFirstName() { return firstName; }
<a id="BABFFGJA" name="BABFFGJA"></a>
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.
<a href="#BABGGADH">Example 1-14</a> shows how to use the @ReturnUpdate
annotation.
Example 1-14 Usage of the @ReturnUpdate Annotation
@ReturnUpdate public String getFirstName() { return firstName; }
<a id="BABHAEGH" name="BABHAEGH"></a>
Using TopLink JPA Extensions for Optimistic Locking
TopLink defines one annotation for optimistic locking–@OptimisticLocking
(see <a href="#BABFFBJJ">"How to Use the @OptimisticLocking Annotation"</a>).
For more information, see the following:
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/undtldev.htm#BABDIIJF">Optimistic Locking</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/descfg.htm#BCGGBAJE">Configuring an Optimistic Locking Policy</a>
<a id="BABFFBJJ" name="BABFFBJJ"></a>
How to Use the @OptimisticLocking Annotation
You can use the @OptimisticLocking
annotation to specify the type of optimistic locking that TopLink should use when updating or deleting entities.
Note: TopLink supports additional optimistic locking policies beyond what is supported through the JPA specification (such as@Version ). 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 { ... }
<a href="#BABGIDIC">Table 1-15</a> lists attributes of the @OptimisticLocking
annotation.
Table 1-15 Attributes of the @OptimisticLocking Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the type ( The following are the valid values for the
|
|
optional |
|
Set this attribute to an array of For an optimistic locking policy of type <a href="#CJAHGDGE">SELECTED_COLUMNS</a>, this annotation member becomes a required field. Note: TopLink will throw an exception if you set the <a href="#CJAHGDGE">SELECTED_COLUMNS</a> type, but fail to specify the |
empty |
optional |
|
Set the value of this attribute to a By enabling cascading you configure TopLink 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 <a href="#CJACFHAD">VERSION_COLUMN</a> locking. For more information, see the following:
|
|
optional |
Note: Setting an You can specify |
<a href="#BABCDJHJ">Example 1-15</a> shows how to use the @OptimisticLocking
annotation with the ALL_COLUMNS
type.
Example 1-15 Usage of the @OptimisticLocking Annotation - ALL_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=ALL_COLUMNS) public class Employee implements Serializable{ private Integer id; private String firstName; private String lastName; ... }
<a href="#BABGABBB">Example 1-16</a> shows how to use the @OptimisticLocking
annotation with the CHANGED_COLUMNS
type.
Example 1-16 Usage of the @OptimisticLocking Annotation - CHANGED_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=CHANGED_COLUMNS) public class Employee implements Serializable{ private Integer id; private String firstName; private String lastName; ... }
<a href="#BABBCHDH">Example 1-17</a> shows how to use the @OptimisticLocking
annotation with the SELECTED_COLUMNS
type.
Example 1-17 Usage of the @OptimisticLocking Annotation - SELECTED_COLUMNS
@Entity @Table(name="EMPLOYEE") @OptimisticLocking( type=SELECTED_COLUMNS, selectedColumns={@Column(name="id"), @Column(name="lastName")} ) public class Employee implements Serializable{ @Id private Integer id; private String lastName; private String lastName; ... }
<a href="#BABBAIGH">Example 1-18</a> shows how to use the @OptimisticLocking
annotation with the VERSION_COLUMN
type.
Example 1-18 Usage of the @OptimisticLocking Annotation - VERSION_COLUMN
@Entity @Table(name="EMPLOYEE") @OptimisticLocking(type=VERSION_COLUMN, cascade=true) public class Employee implements Serializable{ private String firstName; private String lastName; @Version private int version; ... }
<a id="BABBIJAC" name="BABBIJAC"></a>
Using TopLink JPA Extensions for Stored Procedure Query
TopLink defines the following stored procedure query annotations:
-
@NamedStoredProcedureQuery
(see <a href="#BABCEAEH">"How to Use the @NamedStoredProcedureQuery Annotation"</a>); -
@NamedStoredProcedureQueries
(see <a href="#BABGDBCA">"How to Use the @NamedStoredProcedureQueries Annotation"</a>).
You can execute a stored procedure query like any other named query (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#CACFBJCI">Named Queries</a>"). For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/prt_qur.htm#BABCBADI">Queries</a>".
<a id="BABCEAEH" name="BABCEAEH"></a>
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 { ... }
<a href="#BABHCIJD">Table 1-16</a> lists attributes of the @NamedStoredProcedureQuery
annotation.
Table 1-16 Attributes of the @NamedStoredProcedureQuery Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the unique |
no default |
required |
|
Set this attribute to an array of |
empty |
optional |
|
Set this attribute to the |
|
optional |
|
Set this attribute to the |
empty |
optional |
|
Set this attribute to the |
no default |
required |
|
Set this attribute to the |
|
optional |
|
Set the value of this attribute to an array of The following are attributes of the
For more information, see the following:
|
empty |
optional |
<a href="#BABCFFIJ">Example 1-19</a> shows how to use the @NamedStoredProcedureQuery
annotation.
Example 1-19 Usage of the @NamedStoredProcedureQuery Annotation
@Entity @Table(name="EMPLOYEE") @NamedStoredProcedureQuery( name="ReadEmployee", procedureName="Read_Employee", resultClass="Employee.class", storedProcedureParameters={ @StoredProcedureParameter(queryParamater="EMP_ID")} ) public class Employee implements Serializable{ ... }
<a id="BABGDBCA" name="BABGDBCA"></a>
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 { ... }
<a href="#BABCECFE">Table 1-17</a> lists attributes of the @NamedStoredProcedureQueries
annotation.
Table 1-17 Attributes of the @NamedStoredProcedureQueries Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the array of For more information, see <a href="#BABCEAEH">"How to Use the @NamedStoredProcedureQuery Annotation"</a> |
no default |
required |
<a id="CACDJBDH" name="CACDJBDH"></a>
Using TopLink JPA Extensions for JDBC
TopLink JPA provides persistence unit properties that you can define in a persistence.xml
file to configure how TopLink will use the connections returned from the data source used. These properties are devided into the two following categories:
-
Options that you can use to configure how TopLink communicates with the JDBC connection (see <a href="#CJAIFDGD">"How to Use TopLink JPA Extensions for JDBC Connection Communication"</a>).
-
Options that you can use to configure TopLink own connection pooling (see <a href="#CJADIGAF">"How to Use TopLink JPA Extensions for JDBC Connection Pooling"</a>).
<a id="CJAIFDGD" name="CJAIFDGD"></a>
How to Use TopLink JPA Extensions for JDBC Connection Communication
<a href="#CJAJGAEC">Table 1-18</a> lists the TopLink JPA persistence unit properties that you can define in a persistence.xml
file to configure how TopLink communicates with the JDBC connection.
Table 1-18 TopLink JPA Persistence Unit Properties for JDBC Connection Communication
Property | Usage | Default |
---|---|---|
<a id="toplink.jdbc.bind-parameters_persistence.xml" name="toplink.jdbc.bind-parameters_persistence.xml"></a>
|
Control whether or not the query uses parameter binding. Note: this property applies when used in a Java SE environment. For more information, see "<a href="http://download-west.oracle.com/docs/cd/B32110_01/web.1013/b28218/optimiz.htm#i1124456">Parameterized SQL (Binding) and Prepared Statement Caching</a>". The following are the valid values:
Example: <property name="toplink.jdbc.bind-parameters" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_BIND_PARAMETERS, "false"); |
|
|
Enable or disable TopLink's generation of database platform-specific SQL (as opposed to generic SQL). Note: this property applies when used both in a Java SE and Java EE environment. The following are the valid values:
Example: <property name="toplink.jdbc.native-sql" value="true"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.NATIVE_SQL, "true"); |
|
|
Specify the use of batch writing to optimize transactions with multiple write operations. Set the value of this property into the session at deployment time. Note: This property applies when used both in a Java SE and Java EE environment. The following are the valid values:
Note: if you set any other value, TopLink will throw an exception. Example: <property name="toplink.jdbc.batch-writing" value="BUFFERED"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.BATCH_WRITING, "BUFFERED"); |
|
|
The number of statements held when using internal statement caching. Set the value at the deployment time. Note: this property applies when used both in a Java SE and Java EE environment. Valid values: Example: <property name="toplink.jdbc.cache-statements.size" value="2"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.CACHE_STATEMENTS_SIZE, "2"); |
50 |
<a id="toplink.jdbc.driver" name="toplink.jdbc.driver"></a>
|
The class name of the JDBC driver you want to use, fully qualified by its package name. This class must be on your application classpath. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ). Example: <property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver"); |
|
<a id="toplink.jdbc.password" name="toplink.jdbc.password"></a>
|
The password for your JDBC user. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ). Example: <property name="toplink.jdbc.password" value="tiger"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_PASSWORD, "tiger"); |
|
<a id="toplink.jdbc.url" name="toplink.jdbc.url"></a>
|
The JDBC connection URL required by your JDBC driver. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ) Example: <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@MYHOST:1521:MYSID"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_URL, "jdbc:oracle:thin:@MYHOST:1521:MYSID"); |
|
<a id="toplink.jdbc.user" name="toplink.jdbc.user"></a>
|
The user name for your JDBC user. Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ) Example: <property name="toplink.jdbc.url" value="scott"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_USER, "scott"); |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="CJADIGAF" name="CJADIGAF"></a>
How to Use TopLink JPA Extensions for JDBC Connection Pooling
<a href="#CJACCJFI">Table 1-19</a> lists the TopLink JPA persistence unit properties that you can define in a persistence.xml
file to configure TopLink internal connection pooling (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/daun.htm#CHDHEIJE">Internal Connection Pools</a>").
Table 1-19 TopLink JPA Persistence Unit Properties for JDBC Connection Pooling
Property | Usage | Default |
---|---|---|
|
The maximum number of connections allowed in the JDBC read connection pool. Note: this property applies when used in a Java SE environment. Valid values: Example: <property name="toplink.jdbc.read-connections.max" value="3"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_MAX, "3"); |
2 |
|
The minimum number of connections allowed in the JDBC read connection pool. Note: this property applies when used in a Java SE environment. Valid values: Example: <property name="toplink.jdbc.read-connections.min" value="1"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_MIN, "1"); |
2 |
|
Specify whether or not to allow concurrent use of shared read connections. Note: this property applies when used in a Java SE environment. The following are the valid values:
Example: <property name="toplink.jdbc.read-connections.shared" value="true"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_SHARED, "true"); |
|
|
The maximum number of connections allowed in the JDBC write connection pool. Note: this property applies when used in a Java SE environment. Valid values: Example: <property name="toplink.jdbc.write-connections.max" value="5"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_WRITE_CONNECTIONS_MAX, "5"); |
10 |
|
The maximum number of connections allowed in the JDBC write connection pool. Note: this property applies when used in a Java SE environment. Valid values: Example: <property name="toplink.jdbc.write-connections.min" value="2"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(ToplinkProperties.JDBC_WRITE_CONNECTIONS_MIN, "2"); |
5 |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="CACBJEEH" name="CACBJEEH"></a>
Using TopLink JPA Extensions for Logging
<a href="#CJAHJIJH">Table 1-20</a> lists the TopLink JPA persistence unit properties that you can define in a persistence.xml
file to configure TopLink logging.
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#i1122078">Logging</a>".
Table 1-20 TopLink JPA Persistence Unit Properties for Logging
Property | Usage | Default |
---|---|---|
|
Select the type of logger to use: The following are the valid values:
Example: <property name="toplink.logging.logger" value="acme.loggers.MyCustomLogger" /> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_LOGGER, "acme.loggers.MyCustomLogger" /> |
|
<a id="toplink.logging.level" name="toplink.logging.level"></a>
|
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
Example: <property name="toplink.logging.level" value="INFO"/> Example: property import java.util.logging.Level; import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_LEVEL, Level.INFO); |
|
<a id="toplink.logging.timestamp" name="toplink.logging.timestamp"></a>
|
Control whether the timestamp is logged in each log entry. The following are the valid values:
Example: <property name="toplink.logging.timestamp" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_TIMESTAMP, "false"); |
|
<a id="toplink.logging.thread" name="toplink.logging.thread"></a>
|
Control whether a thread identifier is logged in each log entry. The following are the valid values:
Example: <property name="toplink.logging.thread" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_THREAD, "false"); |
|
<a id="toplink.logging.session" name="toplink.logging.session"></a>
|
Control whether a TopLink session identifier is logged in each log entry. The following are the valid values:
Example: <property name="toplink.logging.session" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_SESSION, "false"); |
|
<a id="toplink.logging.exceptions" name="toplink.logging.exceptions"></a>
|
Control whether the exceptions thrown from within the TopLink 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:
Example: <property name="toplink.logging.exceptions" value="true"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_EXCEPTIONS, "true"); |
|
|
Specify a file location for the log output (instead of the standard out). Note: this property applies when used in a Java SE environment. Valid values: a string location to a directory in which you have write access. The location may be relative to your current working directory or absolute. Example: <property name="toplink.logging.file" value="C:\myout\"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.LOGGING_FILE, "C:\myout\"); |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="CACFFJFD" name="CACFFJFD"></a>
Using TopLink JPA Extensions for Session, Target Database and Target Application Server
<a href="#CJAEBIJC">Table 1-21</a> lists the TopLink JPA persistence unit properties that you can define in a persistence.xml
file to configure TopLink extensions for session, as well as the target database and application server.
Table 1-21 TopLink JPA Persistence Unit Properties for Database, Session, and Application Server
Property | Usage | Default |
---|---|---|
<a id="toplink.session-name" name="toplink.session-name"></a>
|
Specify the name by which the TopLink session is stored in the static session manager. Use this option if you need to access the TopLink shared session outside of the context of the JPA or to use a pre-existing TopLink session configured through a TopLink Valid values: a valid TopLink session name that is unique in a server deployment. Example: <property name="toplink.session-name" value="MySession"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.SESSION_NAME, "MySession"); |
TopLink generated unique name. |
<a id="CJACBJGJ" name="CJACBJGJ"></a> |
Specify persistence information loaded from the TopLink session configuration file ( You can use this option as an alternative to annotations and deployment XML. If you specify this property, TopLink will override all class annotation and the object-relational mapping from the Indicate the session by setting the 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. Example: <property name="toplink.session-xml" value="mysession.xml"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.SESSION_XML, "mysession.xml"); |
|
|
Specify a descriptor event listener to be added during bootstrapping. Valid values: qualified class name for a class that implements the Example: <property name="toplink.session-event-listener" value="mypackage.MyClass.class"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.SESSION_EVENT_LISTENER_CLASS, "mypackage.MyClass.class"); |
|
|
Enable or disable the default copying of all named queries (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#CACFBJCI">Named Queries</a>") from the descriptors to the session. These queries include the ones defined using TopLink API, descriptor amendment methods (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/descun.htm#CHEIGIHG">Amendment Methods</a>"), and so on. The following are the valid values:
Example: <property name="toplink.session.include.descriptor.queries" value="false"/> Example: property import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.INCLUDE_DESCRIPTOR_QUERIES, "false"); |
|
<a id="toplink.target-database" name="toplink.target-database"></a>
|
Specify the type of database that your JPA application uses. The The following are the valid values for the
You can also set the value to the fully qualified classname of a subclass of the Example: <property name="toplink.target-database" value="Oracle"/> Example: property import oracle.toplink.config.TargetDatabase; import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.TARGET_DATABASE, TargetDatabase.Oracle); |
|
<a id="toplink.target-server" name="toplink.target-server"></a>
|
Specify the type of application server that your JPA application uses: The following are the valid values for the
Example: <property name="toplink.target-server" value="OC4J_10_1_3"/> Example: property import oracle.toplink.config.TargetServer; import oracle.toplink.config.TopLinkProperties; propertiesMap.put(TopLinkProperties.TARGET_SERVER, TargetServer.OC4J_10_1_3); |
|
For information about the configuration of platforms, see the following:
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/undtldev.htm#BABGCJBJ">Understanding Target Platforms</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/asinteg.htm#BABCJCGB">Integrating TopLink with an Application Server</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/prjdaun.htm#BABHABII">Projects and Platforms</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/daun.htm#CACBHFGE">Database Platforms</a>
For information about the use of annotations as opposed to persistence unit properties and vice versa, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="CACIJBBA" name="CACIJBBA"></a>
Using TopLink JPA Extensions for Schema Generation
<a href="#CJAJIIIA">Table 1-22</a> lists the TopLink JPA persistence unit properties that you can define in a persistence.xml
file to configure schema generation.
Table 1-22 TopLink JPA Persistence Unit Properties for Schema Generation
Property | Usage | Default |
---|---|---|
<a id="toplink.ddl-generation" name="toplink.ddl-generation"></a>
<a id="CJAGHFGI" name="CJAGHFGI"></a> |
Specify what Data Definition Language (DDL) generation action you want for your JPA entities. To specify the DDL generation target, see <a href="#CJAHICAC">toplink.ddl-generation.output-mode</a>. The following are the valid values for the
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 Example: <property name="toplink.ddl-generation" value="create-tables"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.DDL_GENERATION, EntityManagerFactoryProvider.CREATE_ONLY); |
|
<a id="toplink.application-location" name="toplink.application-location"></a>
<a id="CJAFGEBH" name="CJAFGEBH"></a> |
Specify where TopLink should write generated DDL files (see <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> and <a href="#CJAEEFBE">toplink.drop-ddl-jdbc-file-name</a>). Files are written if <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to anything other than 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, TopLink will append one valid for your operating system. Example: <property name="toplink.application-location" value="C:\ddl\"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.APP_LOCATION, "C:\ddl\"); |
|
<a id="toplink.create-ddl-jdbc-file-name" name="toplink.create-ddl-jdbc-file-name"></a>
<a id="CJAIIDIB" name="CJAIIDIB"></a> |
Specify the file name of the DDL file that TopLink generates containing SQL statements to create tables for JPA entities. This file is written to the location specified by <a href="#CJAFGEBH">toplink.application-location</a> when <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to 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 <a href="#CJAFGEBH">toplink.application-location</a> + <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> is a valid file specification for your operating system. Example: <property name="toplink.create-ddl-jdbc-file-name" value="create.sql"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.CREATE_JDBC_DDL_FILE, "create.sql"); |
|
<a id="toplink.drop-ddl-jdbc-file-name" name="toplink.drop-ddl-jdbc-file-name"></a>
<a id="CJAEEFBE" name="CJAEEFBE"></a> |
Specify the file name of the DDL file that TopLink generates containing the SQL statements to drop tables for JPA entities. This file is written to the location specified by <a href="#CJAFGEBH">toplink.application-location</a> when <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to 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 <a href="#CJAFGEBH">toplink.application-location</a> + <a href="#CJAEEFBE">toplink.drop-ddl-jdbc-file-name</a> is a valid file specification for your operating system. Example: <property name="toplink.drop-ddl-jdbc-file-name" value="drop.sql"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.DROP_JDBC_DDL_FILE, "drop.sql"); |
|
<a id="toplink.ddl-generation.output-mode" name="toplink.ddl-generation.output-mode"></a>
<a id="CJAHICAC" name="CJAHICAC"></a> |
Use this property to specify the DDL generation target. The following are the valid values for the
Example: <property name="toplink.ddl-generation.output-mode" value="database"/> Example: property import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider; propertiesMap.put(EntityManagerFactoryProvider.DDL_GENERATION_MODE, EntityManagerFactoryProvider.DDL_DATABASE_GENERATION); |
Container or Java EE mode: EntityManagerFactoryProvider. Bootstrap or Java SE mode: EntityManagerFactoryProvider. |
For information about the use of annotations as opposed to persistence unit properties and vice versa, see <a href="#CJAFAHEJ">"What You May Need to Know About Overriding Annotations"</a>.
<a id="BABIDJEG" name="BABIDJEG"></a>
Using TopLink JPA Extensions for Tracking Changes
Within a transaction, TopLink automatically tracks entity changes.
TopLink defines one annotation for tracking changes–@ChangeTracking
(see <a href="#BABGGBIJ">"How to Use the @ChangeTracking Annotation"</a>).
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowund.htm#CIHJJAGI">Unit of Work and Change Policy</a>".
<a id="BABGGBIJ" name="BABGGBIJ"></a>
How to Use the @ChangeTracking Annotation
Use the @ChangeTracking
annotation to set the unit of work's change policy.
@Target({TYPE}) @Retention(RUNTIME) public @interface ChangeTracking { ... }
Note: This is an optimization feature that lets you tune the way TopLink 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:
|
<a href="#BABCBEBA">Table 1-23</a> lists attributes of the @ChangeTracking
annotation.
Table 1-23 Attributes of the @ChangeTracking Annotation
Attribute | Description | Default | Required or Optional |
---|---|---|---|
|
Set this attribute to the type of the change tracking ( The following are the valid values for the
|
|
optional |
<a href="#BABJHDGJ">Example 1-20</a> shows how to use the @ChangeTracking
annotation.
Example 1-20 Usage of @ChangeTracking Annotation
@Entity @Table(name="EMPLOYEE") @ChangeTracking(OBJECT) ( public class Employee implements Serializable { ... }
<a id="CACEGCFG" name="CACEGCFG"></a>
Using TopLink JPA Query Customization Extensions
This section describes the following:
-
<a href="#CACJJADJ">How to Use TopLink JPA Query Hints</a>
-
<a href="#CACIJDHJ">How to Use TopLink Query API in JPA Queries</a>
<a id="CACJJADJ" name="CACJJADJ"></a>
How to Use TopLink JPA Query Hints
<a href="#CJADBHCE">Table 1-24</a> lists the TopLink JPA query hints that you can specify when you construct a JPA query, as <a href="#CJAGAFIC">Example 1-21</a> shows, or when you specify a JPA query using the @QueryHint
annotation (see Section 8.3.1 "NamedQuery Annotation" of the JPA specification), as <a href="#CJADBIHF">Example 1-22</a> shows.
When you set a hint, you can set the value using the public static final field in the appropriate configuration class in oracle.toplink.config
package, including the following:
-
PessimisticLock
-
TopLinkQueryHints
-
HintValues
<a href="#CJAGAFIC">Example 1-21</a> and <a href="#CJADBIHF">Example 1-22</a> show how to set the value of hint toplink.jdbc.bind-parameters
using the TopLinkQueryHints
configuration class to set the name of the hint, and the HintValues
configuration class to set the value.
Example 1-21 Specifying a TopLink JPA Query Hint
import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; Customer customer = (Customer)entityMgr.createNamedQuery("findCustomerBySSN"). setParameter("SSN", "123-12-1234"). setHint(TopLinkQueryHints.BIND_PARAMETERS, HintValues.PERSISTENCE_UNIT_DEFAULT). getSingleResult();
Example 1-22 Specifying a TopLink JPA Query Hint with @QueryHint
import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @Entity @NamedQuery( name="findEmployeeByDept", query="SELECT e FROM Employee e WHERE e.dept=:deptNum" hints={@QueryHint= {name=TopLinkQueryHints.BIND_PARAMETERS, value=HintValues.TRUE} } ) public class Employee implements Serializable { ... }
Table 1-24 TopLink JPA Query Hints
Hint | Usage | Default |
---|---|---|
|
Specify how the query should interact with the TopLink cache. TopLink 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.Cache invalidation is another strategy that you can use. Consider the following example, that clears the current persistence context as well as invalidates the cache: public static void clearCache(EntityManager em){ em.clear(); oracle.toplink.ejb.cmp3.EntityManager tlem = (oracle.toplink.ejb.cmp3.EntityManager)em; tlem.getActiveSession() .getIdentityMapAccessor() .initializeAllIdentityMaps(); } For more information, see the following: - <a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/cachun.htm#sthref4981">Session Cache</a> - <a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#i1165073">Using In-Memory Queries</a> The following are the valid values for the
Note: the default value is related to the value that you defined in the descriptor for the For more information, see " <a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#CACDAJCC">Configuring Cache Usage for In-Memory Queries</a>". Example: JPA Query API import oracle.toplink.config.CacheUsage; import oracle.toplink.config.TopLinkQueryHints; query.setHint(TopLinkQueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly); Example: import oracle.toplink.config.CacheUsage; import oracle.toplink.config.TargetDatabase; @QueryHint(name=TopLinkQueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheOnly); |
|
<a id="toplink.jdbc.bind-parameters_query.hint" name="toplink.jdbc.bind-parameters_query.hint"></a>
|
Control whether or not the query uses parameter binding. For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/optimiz.htm#i1124456">Parameterized SQL (Binding) and Prepared Statement Caching</a>". The following are the valid values for the
Example: JPA Query API import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint(TopLinkQueryHints.BIND_PARAMETERS, HintValues.TRUE); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TargetDatabase; @QueryHint(name=TopLinkQueryHints.BIND_PARAMETERS, value=HintValues.TRUE); |
|
|
Specify the number of rows that should be fetched from the database when more rows are needed. For large queries that return a large number of objects you can configure the row fetch size used in the query to improve performance by reducing the number database hits required to satisfy the selection criteria. Most JDBC drivers default to a fetch size of 10, so if you are reading 1000 objects, increasing the fetch size to 256 can significantly reduce the time required to fetch the query's results. The optimal fetch size is not always obvious. Usually, a fetch size of one half or one quarter of the total expected result size is optimal. Note that if you are unsure of the result set size, incorrectly setting a fetch size too large or too small can decrease performance. A value of 0 means the JDBC driver returns results one row at a time. Note: this property is dependent on the JDBC driver support. Valid values: |
0 |
|
Specify the number of seconds TopLink will wait on a query before throwing a A value of 0 means TopLink will never time-out a query. Note: this property is dependent on the JDBC driver support. Valid values: |
0 |
<a id="toplink.pessimistic-lock" name="toplink.pessimistic-lock"></a>
|
Control whether or not pessimistic locking is used. The following are the valid values for the
Example: JPA Query API import oracle.toplink.config.PessimisticLock; import oracle.toplink.config.TopLinkQueryHints; query.setHint(TopLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait); Example: import oracle.toplink.config.PessimisticLock; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.PESSIMISTIC_LOCK, value=PessimisticLock.LockNoWait); |
|
|
Supply TopLink with batching information so subsequent queries of related objects can be optimized in batches instead of being retrieved in one large joined read. Batching is only allowed on queries that have a single object in their select clause. Allow joining of the attributes. This is different from JP QL joining because it allows multilevel fetch joins. 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 Example: JPA Query API import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint("toplink.batch", "e.address"); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.BATCH, value="e.address"); |
|
|
Allow joining of the attributes. This is similar to 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 oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint("toplink.join-fetch", "e.address"); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.FETCH, value="e.address"); |
|
<a id="toplink.refresh" name="toplink.refresh"></a>
|
Control whether or not to update the TopLink session cache with objects that the query returns. The following are the valid values for the
Example: JPA Query API import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint(TopLinkQueryHints.REFRESH, HintValues.TRUE); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.REFRESH, value=HintValues.TRUE); |
|
|
Retrieve read-only results back from the query: on nontransactional read operations, where the requested entity types are stored in the shared cache, you can request that the shared instance be returned instead of a detached copy. You must set the read-only flag for the report query to Note: You should never modify objects returned from the shared cache. The following are the valid values for the
Example: JPA Query API import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint(TopLinkQueryHints.RETURN_SHARED, HintValues.TRUE); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.RETURN_SHARED, value=HintValues.TRUE); |
|
|
Configure the concrete class that TopLink 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 Note: Typically, you would execute these queries by calling the Note: Specify the class without the TopLink will throw an exception, if you use this hint with a class that does not implement the Example: JPA Query API import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; query.setHint("toplink.result-collection-type", "java.util.ArrayList.class"); Example: import oracle.toplink.config.HintValues; import oracle.toplink.config.TopLinkQueryHints; @QueryHint(name=TopLinkQueryHints.RESULT_COLLECTION_TYPE, value="java.util.ArrayList"); |
java.util.Vector |
<a id="CACIJDHJ" name="CACIJDHJ"></a>
How to Use TopLink Query API in JPA Queries
TopLink JPA provides a TopLink implementation class for each JPA persistence interface. By casting to the TopLink implementation class, you have full access to TopLink functionality.
This section provides the following examples:
-
<a href="#CJAFGFEJ">Creating a JPA Query Using the TopLink Expressions Framework</a>
-
<a href="#CJACFIGB">Creating a JPA Query Using a TopLink DatabaseQuery</a>
-
<a href="#CJABCFBJ">Creating a JPA Query Using a TopLink Call Object</a>
-
<a href="#CJAFCACJ">Using Named Parameters in a Native Query</a>
-
<a href="#CJADDHGG">Using Java Persistence Query Language Positional Parameters in a Native Query</a>
-
<a href="#CJABHABE">Using JDBC-Style Positional Parameters in a Native Query</a>
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/prt_qur.htm#BABCBADI">Understanding TopLink Queries</a>".
<a id="CJAFGFEJ" name="CJAFGFEJ"></a>
Creating a JPA Query Using the TopLink Expressions Framework
TopLink provides an expression framework with which you can express queries in a database-neutral fashion as an alternative to raw SQL.
<a href="#CJAFDHAG">Example 1-23</a> shows how to cast an entity manager to access a TopLink persistence provider createQuery
method that takes a TopLink Expression
.
Example 1-23 Creating a Query with the TopLink Expressions Framework
((oracle.toplink.ejb.cmp3.EntityManager)entityManager.getDelegate()). createQuery(Expression expression, Class resultType);
TopLink 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 theEmployee
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, TopLink 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)));
TopLink 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 "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/expres.htm#CJAGGAGJ">Understanding the TopLink Expressions</a>".
<a id="CJACFIGB" name="CJACFIGB"></a>
Creating a JPA Query Using a TopLink DatabaseQuery
A TopLink DatabaseQuery
is a query object that provides a rich API for handling a variety of database query requirements, including reading and writing at the object level and at the data level.
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#CACFEDJD">Understanding the TopLink DatabaseQuery</a>".
<a href="#CJAEGECE">Example 1-24</a> shows how to cast a JPA query from an entity manager to access a TopLink persistence provider setDatabaseQuery
method that takes a TopLink DatabaseQuery
.
Example 1-24 DatabaseQuery
((oracle.toplink.ejb.cmp3.EJBQuery)query).setDatabaseQuery(DatabaseQuery query);
<a href="#CJAGEAAB">Example 1-25</a> shows how to cast a JPA query from an entity manager to access a TopLink persistence provider setDatabaseQuery
method that takes a TopLink DataReadQuery
initialized with a TopLink SQLCall
object that specifies a SELECT
. This query will return one or more objects.
Example 1-25 DatabaseQuery with Selecting Call
((oracle.toplink.ejb.cmp3.EJBQuery)query). setDatabaseQuery(new DataReadQuery(new SQLCall("SELECT...")));
<a href="#CJAFCADG">Example 1-26</a> shows how to cast a JPA query from an entity manager to access a TopLink persistence provider setDatabaseQuery
method that takes a TopLink DataModifyQuery
initialized with a TopLink 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.
Example 1-26 DatabaseQuery with Non-Selecting Call
((oracle.toplink.ejb.cmp3.EJBQuery)query). setDatabaseQuery(new DataModifyQuery(new SQLCall("UPDATE...")));
<a id="CJABCFBJ" name="CJABCFBJ"></a>
Creating a JPA Query Using a TopLink Call Object
Using DatabaseQuery
method setCall
, you can define your own TopLink Call
to accommodate a variety of data source options such as SQL stored procedures and stored functions, EJB QL queries, and EIS interactions.
<a href="#CJABJHIH">Example 1-27</a> shows how to cast a JPA query from an entity manager to access a TopLink persistence provider getDatabaseQuery
method to set a new SQLCall
.
Example 1-27 Call
((oracle.toplink.ejb.cmp3.EJBQuery)query). getDatabaseQuery().setCall(new SQLCall("..."));
For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qryun.htm#CACJHDCJ">Understanding TopLink Call Queries</a>".
<a id="CJAFCACJ" name="CJAFCACJ"></a>
Using Named Parameters in a Native Query
Using TopLink, you can specify a named parameter in a native query using the TopLink #
convention (see <a href="#CJAFCADE">Example 1-28</a>).
Support for the TopLink #
convention is helpful if you are already familiar with TopLink queries or if you are migrating TopLink queries to a JPA application.
Example 1-28 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();
<a id="CJADDHGG" name="CJADDHGG"></a>
Using Java Persistence Query Language Positional Parameters in a Native Query
Using TopLink, you can specify positional parameters in a native query using the Java Persistence Query Language positional parameter convention ?n
to specify a parameter by number.
<a href="#CJAIFGEH">Example 1-29</a> 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%"
.
Example 1-29 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 <a href="#CJAJACFB">Example 1-30</a> shows. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "D%"
.
Example 1-30 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();
<a id="CJABHABE" name="CJABHABE"></a>
Using JDBC-Style Positional Parameters in a Native Query
Using TopLink, you can specify positional parameters in a native query using the JDBC-style positional parameter ?
convention.
<a href="#CJAJJIGD">Example 1-31</a> 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%"
.
Example 1-31 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 <a href="#CJACJIAB">Example 1-32</a> shows. In this example, the query string will be SELECT * FROM EMPLOYEE WHERE F_NAME LIKE "D%" AND L_NAME LIKE "D%"
.
Example 1-32 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();
<a id="CACEDCAF" name="CACEDCAF"></a>
Using TopLink 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 FetchType.LAZY
, and TopLink persistence provider will supply all the necessary functionality.
If you are developing your application in a Java SE environment, to configure TopLink JPA to perform lazy loading when the fetch
attribute is set to FetchType.LAZY
, configure either dynamic (see <a href="#DynamicWeaving">"How to Configure Dynamic Weaving"</a>) or static (see <a href="#StaticWeaving">"How to Configure Static Weaving Using the StaticWeave Class on the Command Line"</a>) weaving.
<a href="#CJAJCGDA">Table 1-25</a> lists TopLink JPA support for lazy loading by mapping type.
Table 1-25 TopLink JPA Support for Lazy Loading by Mapping Type
Mapping | Java EE<a id="sthref27" name="sthref27" href="#sthref27" onclick='footdisplay(1,"Fully supported in any container that implements the appropriate container contracts in the EJB 3.0 specification.")'>Foot 1 </a> | Java SE |
---|---|---|
|
TopLink JPA performs lazy loading when the |
TopLink JPA performs lazy loading when the |
|
TopLink JPA performs lazy loading when the |
TopLink JPA performs lazy loading when the |
|
TopLink JPA performs lazy loading when the |
By default, TopLink JPA ignores the To configure TopLink JPA to perform lazy loading when the
|
|
TopLink JPA performs lazy loading when the |
By default, TopLink JPA ignores the To configure TopLink JPA to perform lazy loading when the
|
|
TopLink JPA ignores the |
TopLink JPA ignores the |
Footnote 1 Fully supported in any container that implements the appropriate container contracts in the EJB 3.0 specification.
For more information, see the following:
-
<a href="#CACDIDAH">What You May Need to Know About Weaving</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/optimiz.htm#BEEGGDDB">Read Optimization Examples</a>
-
<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/mapcfg.htm#CEGDDEEA">Configuring Indirection</a>
<a id="DynamicWeaving" name="DynamicWeaving"></a>
How to Configure Dynamic Weaving
When using a one-to-one (see Section 9.1.23 "OneToOne Annotation" of the JPA specification) or many-to-one (see Section 9.1.22 "ManyToOne Annotation" of the JPA specification) mapping in a Java SE environment that permits the use of -javaagent
on the JVM command line, to configure TopLink JPA to perform lazy loading when the annotation attribute fetch
is set to javax.persistence.FetchType.LAZY
, you can use the toplink-agent.jar
file, as follows:
-
Configure your persistence unit with a <a href="#toplink.weaving">
toplink.weaving
</a> extension set totrue
. -
Modify your application JVM command line to include the following:
-javaagent:toplink-agent.jar
-
Ensure that the
toplink-agent.jar
is in your application classpath.
Use this option to weave applicable class files one at a time, as they are loaded at run time, when the number of classes is few or the time taken to weave the classes is short. If the number of class files is large or the time required to weave the classes is long, consider using static weaving (see <a href="#StaticWeaving">"How to Configure Static Weaving Using the StaticWeave Class on the Command Line"</a> or <a href="#CJAGHHFH">"How to Use Static Weaving with the weave Ant Task"</a>).
How to Configure Static Weaving Using the Persistence Unit Property
Configure your persistence unit with a <a href="#CJAFECEI">toplink.weaving</a> property set to static
.
<a id="StaticWeaving" name="StaticWeaving"></a>
How to Configure Static Weaving Using the StaticWeave Class on the Command Line
When using a one-to-one (see Section 9.1.23 "OneToOne Annotation" of the JPA specification) or many-to-one (see Section 9.1.22 "ManyToOne Annotation" of the JPA specification) mapping in a Java SE environment that does not permit the use of -javaagent
on the JVM command line, to configure TopLink JPA to perform lazy loading when annotation attribute fetch
is set to javax.persistence.FetchType.LAZY
, you can use the StaticWeave
class on the command line.
Use this option to weave all applicable class files at buildtime so that you can deliver pre-woven class files. By doing so, you can improve application performance by eliminating the runtime weaving step required by dynamic weaving (see <a href="#DynamicWeaving">"How to Configure Dynamic Weaving"</a>).
Alternatively, you can do this using Ant (see <a href="#CJAGHHFH">"How to Use Static Weaving with the weave Ant Task"</a>).
To use the StaticWeave
class, do the following:
-
Ensure that the
toplink.jar
file is in your system classpath. -
Execute the
StaticWeave
class on the command line as follows:java oracle.toplink.weaving.StaticWeave [arguments] <source> <target>
<a href="#CJAEGCGC">Example 1-33</a> shows how to use the
StaticWeave
class on Windows systems. <a href="#CJAEIGGH">Table 1-26</a> lists the arguments of this class.<a id="CJAEGCGC" name="CJAEGCGC"></a>Example 1-33 Executing StaticWeave on the Command Line
java oracle.toplink.weaving.StaticWeave -persistenceinfo c:\foo-containing-persistencexml.jar -classpath c:\classpath1;c:\classpath2 c:\foo-source.jar c:\foo-target.jar
<a id="sthref29" name="sthref29"></a><a id="CJAEIGGH" name="CJAEIGGH"></a>Table 1-26 TopLink StaticWeave Class Command Line Arguments
<thead>
Argument Description Default Required or Optional <a id="CJAEFHEI" name="CJAEFHEI"></a> -persistenceinfo
Specifies the location of the
persistence.xml
file if it is not in the same location as the source (see <a href="#CJAIHEBF">-classpath
</a>).Optional
<a id="CJAIHEBF" name="CJAIHEBF"></a> -classpath
Specifies the location of the Java source files to weave: either a directory or a JAR file. For Windows, use delimiter
;
and for Unix, use delimiter:
.If the
persistence.xml
file is not in this location, you must specify the location of thepersistence.xml
using the <a href="#CJAEFHEI">-persistenceinfo
</a> attribute.Required
-log
Specifies a logging file.
See "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#i1122078">Logging</a>".
Optional
-loglevel
Specifies the amount and detail of log output.
Valid
java.util.logging.Level
values are as follows:-
OFF
–disables logging. -
SEVERE
–logs exceptions indicating TopLink cannot continue, as well as any exceptions generated during login. This includes a stack trace. -
WARNING
–logs exceptions that do not force TopLink to stop, including all exceptions not logged with severe level. This does not include a stack trace. -
INFO
–logs the login/logout per sever session, including the user name. After acquiring the session, detailed information is logged. -
CONFIG
–logs only login, JDBC connection, and database information. -
FINE
–logs SQL. -
FINER
–similar to warning. Includes stack trace. -
FINEST
–includes additional low level information.
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 thepersistence.xml
using the <a href="#CJAEFHEI">-persistenceinfo
</a> attribute.Required
<target>
Specifies the output location: either a directory or a JAR file.
Required
<tbody>
Note:
If<source>
and<target>
point to the same location and if the<source>
is a directory (not a JAR file), TopLink JPA will weave in place. If<source>
and<target>
point to different locations or if thesource
is a JAR file (as <a href="#CJAEGCGC">Example 1-33</a> shows), TopLink JPA cannot weave in place. -
<a id="CJAGHHFH" name="CJAGHHFH"></a>
How to Use Static Weaving with the weave Ant Task
When using a one-to-one (see Section 9.1.23 "OneToOne Annotation" of the JPA specification) or many-to-one (see Section 9.1.22 "ManyToOne Annotation" of the JPA specification) mapping in a Java SE environment that does not permit the use of -javaagent
on the JVM command line, to configure TopLink JPA to perform lazy loading when annotation attribute fetch
is set to javax.persistence.FetchType.LAZY
, you can use the TopLink JPA weave
Ant task.
Use 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 the deployment performance.
To use the TopLink JPA weave
Ant task, do the following:
-
Configure the
weave
Ant task in your build script as <a href="#CJABDJCB">Example 1-34</a> shows. <a href="#CJAFDEHH">Table 1-27</a> lists the attributes of this task.<a id="CJABDJCB" name="CJABDJCB"></a>Example 1-34 TopLink weave Ant Task
<target name="define.task" description="New task definition for toplink static weaving"/> <taskdef name="weave" classname="oracle.toplink.weaving.StaticWeaveAntTask"/> </target> <target name="weaving" description="perform weaving" depends="define.task"> <weave source="c:\foo.jar" target="c:\wovenfoo.jar" persistenceinfo="c:\foo-containing-persistenceinfo.jar"> <classpath> <pathelement path="c:\foo-dependent.jar"/> </classpath> </weave> </target>
<a id="sthref30" name="sthref30"></a><a id="CJAFDEHH" name="CJAFDEHH"></a>Table 1-27 TopLink weave Ant Task Attributes
<thead>
Attribute Description Default Required or Optional source
Specifies the location of the Java source files to weave: either a directory or a JAR file.
If the
persistence.xml
file is not in this location, you must specify the location of thepersistence.xml
using thepersistenceinfo
attribute.Required
target
Specifies the output location: either a directory or a JAR file.
Required
persistenceinfo
Specifies the location of the
persistence.xml
file if it is not in the same location as the source.Optional
log
Specifies a logging file.
See "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#i1122078">Logging</a>"
Optional
loglevel
Specifies the amount and detail of log output.
Valid
java.util.logging.Level
values are:-
OFF
–disables logging. -
SEVERE
–logs exceptions indicating TopLink cannot continue, as well as any exceptions generated during login. This includes a stack trace. -
WARNING
–logs exceptions that do not force TopLink to stop, including all exceptions not logged with severe level. This does not include a stack trace. -
INFO
–logs the login/logout per sever session, including the user name. After acquiring the session, detailed information is logged. -
CONFIG
–logs only login, JDBC connection, and database information. -
FINE
–logs SQL. -
FINER
–similar to warning. Includes stack trace. -
FINEST
–includes additional low level information.
Level.OFF
Optional
<tbody>
Note:
Ifsource
andtarget
point to the same location and if thesource
is a directory (not a JAR file), TopLink JPA will weave in place. Ifsource
andtarget
point to different locations or if thesource
is a JAR file (as <a href="#CJABDJCB">Example 1-34</a> shows), TopLink JPA cannot weave in place. -
-
Configure the
weave
task with an appropriate<classpath>
element, as <a href="#CJABDJCB">Example 1-34</a> shows, so that TopLink JPA can load all required source classes. -
Execute the Ant task using the command line that <a href="#CJABGHGH">Example 1-35</a> shows.
In this example, the
weave
Ant task is in thebuild.xml
file.<a id="CJABGHGH" name="CJABGHGH"></a>Example 1-35 TopLink JPA weave Ant Task Command Line
ant -lib C:\toplink.jar -f build.xml weave
<tbody>
Note:
You must specify thetoplink.jar
file (the JAR that contains the TopLink JPAweave
Ant task) using the Ant command line-lib
option instead of using thetaskdef
attributeclasspath
.
<a id="CACDIDAH" name="CACDIDAH"></a>
What You May Need to Know About Weaving
Weaving is a technique of manipulating the byte-code of compiled Java classes.
TopLink persistence provider uses weaving for lazy loading (value holder indirection) For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/mapun.htm#CEGHBHEA">Value Holder Indirection</a>".
<a id="CJAFAHEJ" name="CJAFAHEJ"></a>
What You May Need to Know About Overriding Annotations
In JPA, you override any annotation with XML in your object-relational mapping files (see <a href="#CJAJADEB">"Overriding Annotations with XML in JPA"</a>).
In TopLink JPA, you can override any attribute of a TopLink-extended annotation in a TopLink project.xml
file. This overriding mechanism is similar to the JPA's one with the exception that TopLink annotations correspond to a subset of the project.xml
file's elements instead of all elements. Also, in addition annotations extensions, TopLink JPA allows you to use persistence unit properties that you specify in the persistence.xml
file. In some cases, a persistence unit property, if specified, overrides a corresponding TopLink JPA annotation attribute (see <a href="#CJABFEFC">"Overriding Annotations in TopLink JPA"</a>).
Note: By design, TopLink JPA annotations and persistence unit properties are not analogous to the JPA annotations and elements of mapping XML files. |
<a id="CJAJADEB" name="CJAJADEB"></a>
Overriding Annotations with XML in JPA
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 <a href="http://java.sun.com/xml/ns/persistence/orm_1_0.xsd">http://java.sun.com/xml/ns/persistence/orm_1_0.xsd</a>
. 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 <a href="#CJACJBHD">"Disabling Annotations"</a>).
For more information and examples, see Section 10.1 "XML Overriding Rules" of the JPA specification.
<a id="CJACJBHD" name="CJACJBHD"></a>
Disabling Annotations
JPA provides a mechanism that you can use to disable annotaions. 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 Section 9.1.36 "MappedSuperclass Annotation" of the JPA specification), and embedded objects (see Section 9.1.35 "Embedded Annotation" of the JPA specification) 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 <a href="#CJABABHJ">Example 1-36</a> shows.
Example 1-36 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. <a href="#CJAEAEJH">Example 1-37</a> shows how to use the metadata-complete
attribute.
Example 1-37 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" <span class="bold">metadata-complete="true"</span>> <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.
<a id="CJABFEFC" name="CJABFEFC"></a>
Overriding Annotations in TopLink JPA
TopLink JPA provides a set of persistence unit properties that you can specify in your persistence.xml
file, or in a property map file. The persistence unit properties always override the corresponding annotations' attributes.
Similar to TopLink annotations, properties expose some features of TopLink that are currently not available through the use of JPA metadata.
Note: If multiple instances of the same property are set, then TopLink will use the values from the last entry in the list. |
You can also specify the persistence information in the TopLink session configuration file–sessions.xml
(see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#CACIGEBC">Session Configuration and the sessions.xml File</a>"). By setting the <a href="#CJACBJGJ">toplink.session-xml</a> persistence unit property you enable TopLink to override 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 toplink.session-xml
property lets provide session-level configurations that are not supported by persistence unit properties (for example, cache coordination).
Note: You can use tthetoplink.session-xml property as an alternative to annotations and deployment XML. |
</body>
</html>