Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

EclipseLink/Features/JPA Extensions

Contents

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 is intended for Oracle TopLink 11g preview. For documentation on TopLink Essentials, refer to <a href="http://www.oracle.com/technology/products/ias/toplink/JPA/essentials/toplink-jpa-extensions.html">http://www.oracle.com/technology/products/ias/toplink/JPA/essentials/toplink-jpa-extensions.html</a>

This document explains where and how you use the extensions to customize JPA behavior to meet your application requirements.

This document includes the following sections:

  • <a href="#BABFEBAH">Using TopLink JPA Extensions for Mapping</a>

  • <a href="#BABDFDIG">Using TopLink JPA Converters</a>

  • <a href="#BABGDJBC">Using TopLink JPA Extensions for Entity Caching</a>

  • <a href="#BABHBEDD">Using TopLink JPA Extensions for Customization</a>

  • <a href="#BABDDFGA">Using TopLink JPA Extensions for Returning Policy</a>

  • <a href="#BABHAEGH">Using TopLink JPA Extensions for Optimistic Locking</a>

  • <a href="#BABBIJAC">Using TopLink JPA Extensions for Stored Procedure Query</a>

  • <a href="#CACDJBDH">Using TopLink JPA Extensions for JDBC</a>

  • <a href="#CACBJEEH">Using TopLink JPA Extensions for Logging</a>

  • <a href="#CACFFJFD">Using TopLink JPA Extensions for Session, Target Database and Target Application Server</a>

  • <a href="#CACIJBBA">Using TopLink JPA Extensions for Schema Generation</a>

  • <a href="#BABIDJEG">Using TopLink JPA Extensions for Tracking Changes</a>

  • <a href="#CACEGCFG">Using TopLink JPA Query Customization Extensions</a>

  • <a href="#CACEDCAF">Using TopLink JPA Lazy Loading</a>

For more information, see the following:

<a id="BABFEBAH" name="BABFEBAH"></a>

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.

<a id="sthref1" name="sthref1"></a><a id="BABHHCFB" name="BABHHCFB"></a>

Table 1-1 Attributes of the @BasicMap Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

fetch

Set this attribute to the javax.persistence.FetchType enumerated type to define whether TopLink persistence provider has to lazily load or eagerly fetch the value of the field or property.

FetchType.LAZY

optional

keyColumn

Set this attribute to the name of the data column (javax.persistence.Column) that holds the direct map key.

no default

required

keyConverter

Set this attribute to the key converter (java.toplink.annotations.Convert)

@Convert–an equivalent of specifying @Convert("none") resulting in no converter added to the direct map key.

optional

valueColumn

Set this attribute to the name of the value column (javax.persistence.Column) that holds the direct collection data.

@Column

Note: TopLink persistence provider sets the default to the name of the field or property.

optional

valueConverter

Set this attribute to the value converter (java.toplink.annotations.Convert).

@Convert–an equivalent of specifying @Convert("none") resulting in no converter added to the direct map key.

optional



<tbody> </tbody>

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.

<a id="BABFDCCJ" name="BABFDCCJ"></a>

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.

<a id="sthref2" name="sthref2"></a><a id="BABEIFAC" name="BABEIFAC"></a>

Table 1-2 Attributes of the @BasicCollection Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

fetch

The javax.persistence.FetchType enumerated type that defines whether TopLink should lazily load or eagerly fetch the value of the field or property.

FetchType.LAZY

optional

valueColumn

The name of the value column (javax.persistence.Column) that holds the direct collection data.

@Column

Note: TopLink persistence provider sets the default to the name of the field or property.

optional



<tbody> </tbody>

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.

<a id="BABEBJDI" name="BABEBJDI"></a>

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.

<a id="sthref3" name="sthref3"></a><a id="BABFJECG" name="BABFJECG"></a>

Table 1-3 Attributes of the @CollectionTable Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

name

Set this attribute to the String name for your collection table.

empty String

Note: TopLink persistence provider applies the following concatenated String as a default: the name of the source entity + "_" + the name of the relationship property or field of the source entity.

optional

catalog

Set this attribute to the String name of the table's catalog.

empty String

Note: TopLink persistence provider sets the default to the persistence unit's default catalog.

optional

schema

Set this attribute to the String name of the table's schema.

empty String

Note: TopLink persistence provider sets the default to the persistence unit's default schema.

optional

primaryKeyJoinColumns

Set this attribute to an array of javax.persistence.PrimaryKeyJoinColumn instances to specify a primary key column that is used as a foreign key to join to another table. If the source entity uses a composite primary key, you must specify a primary key join column for each field of the composite primary key. If the source entity uses a single primary key, you may choose to specify a primary key join column (optional). Otherwise, TopLink persistence provider will apply the following defaults:

  • javax.persistence.PrimaryKeyJoinColumn name–the same name as the primary key column of the primary table of the source entity;

  • javax.persistence.PrimaryKeyJoinColumn referencedColumnName–the same name of the primary key column of the primary table of the source entity.

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 PrimaryKeyJoinColumn array

optional

uniqueConstraints

Set this attribute to an array of javax.persistence.UniqueConstraint instances that you want to place on the table. These constraints are only used if table generation is in effect.

empty UniqueConstraint array

optional


<a href="#CJAGDAFA">Example 1-3</a> shows how to use the @CollectionTable annotation to specify Employee field responsibilities.

<a id="CJAGDAFA" name="CJAGDAFA"></a>

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.

<a id="BABFADHG" name="BABFADHG"></a>

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;
    }
    ...
}
<a id="sthref4" name="sthref4"></a>

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.


<tbody> </tbody>

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.

<a id="sthref5" name="sthref5"></a><a id="BABFHHEH" name="BABFHHEH"></a>

Table 1-4 Attributes of the @JoinFetch Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

value

Set this attribute to the oracle.toplink.annotations.JoinFetchType enumerated type of the fetch that you will be using.

The following are the valid values for the JoinFetchType:

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

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

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

    Note: outer joining allows for null or empty values.

For more information, see the following:

JoinFetchType.INNER

optional


<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.

<a id="sthref6" name="sthref6"></a><a id="BABJCFIG" name="BABJCFIG"></a>

Table 1-5 Attributes of the @Converter Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

name

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

no default

required

converterClass

Set this attribute to the Class of your converter. This class must implement the TopLink oracle.toplink.mappings.converters.Converter interface.

no default

required


<a href="#BABFHCDB">Example 1-5</a> shows how to use the @Converter annotation to specify Employee field gender.

<a id="BABFHCDB" name="BABFHCDB"></a>

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.

<a id="sthref7" name="sthref7"></a><a id="BABEAFDC" name="BABEAFDC"></a>

Table 1-6 Attributes of the @TypeConverter Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

name

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

no default

required

dataType

Set this attribute to the type stored in the database.

void.class

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

optional

objectType

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

void.class

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

optional


<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.

<a id="BABECICJ" name="BABECICJ"></a>

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.

<a id="sthref8" name="sthref8"></a><a id="BABFCGJF" name="BABFCGJF"></a>

Table 1-7 Attributes of the @ObjectTypeConverter Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

name

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

no default

required

dataType

Set this attribute to the type stored in the database.

void.class

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

optional

objectType

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

void.class

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

optional

conversionValues

Set the value of this attribute to the array of conversion values (instances of ConversionValue: String objectValue and String dataValue. See <a href="#BABJEBJA">Example 1-7</a>) to be used with the object converter.

no default

required

defaultObjectValue

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

empty String

optional


<a href="#BABJEBJA">Example 1-7</a> shows how to use the @ObjectTypeConverter annotation to specify the Employee field gender.

<a id="BABJEBJA" name="BABJEBJA"></a>

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 the oracle.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.

<a id="sthref9" name="sthref9"></a><a id="BABBJEIF" name="BABBJEIF"></a>

Table 1-8 Attributes of the @Convert Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

value

Set this attribute to the String name for your converter.

"none" String

optional


<a href="#BABHHCCH">Example 1-8</a> shows how to use the @Convert annotation to define the Employee field gender.

<a id="BABHHCCH" name="BABHHCCH"></a>

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> </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.

<a id="sthref10" name="sthref10"></a><a id="BABHBIJE" name="BABHBIJE"></a>

Table 1-9 Attributes of the @Cache Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional Override with Persistence Unit Property

<a id="CACDJFCF" name="CACDJFCF"></a>type

Set this attribute to the type (oracle.toplink.annotations.CacheType enumerated type) of the cache that you will be using.

The following are the valid values for the CacheType:

  • FULL–This option provides full caching and guaranteed identity: all objects are cached and not removed.

    Note: this process may be memory-intensive when many objects are read.

  • WEAK–This option is similar to FULL, except that objects are referenced using weak references. This option uses less memory than FULL, allows complete garbage collection and provides full caching and guaranteed identity.

    Oracle recommends using this identity map for transactions that, once started, stay on the server side.

  • SOFT_WEAK–This option is similar to WEAK except that it maintains a most frequently used subcache that uses soft references. The size of the subcache is proportional to the size of the identity map. The subcache uses soft references to ensure that these objects are garbage-collected only if the system is low on memory.

    Oracle recommends using this identity map in most circumstances as a means to control memory used by the cache.

  • HARD_WEAK–This option is similar to SOFT_WEAK except that it maintains a most frequently used subcache that uses hard references. Use this identity map if soft references are not suitable for your platform.

  • CACHE–With this option, a cache identity map maintains a fixed number of objects that you specify in your application. Objects are removed from the cache on a least-recently-used basis. This option allows object identity for the most commonly used objects.

    Note: this option furnishes caching and identity, but does not guarantee identity.

  • NONE–This option does not preserve object identity and does not cache objects. Oracle does not recommend using this option.

CacheType.SOFT_WEAK

optional

  • <a href="#CACGFGJE">toplink.cache.type.<ENTITY></a>

  • <a href="#CACCAEFH">toplink.cache.type.default</a>


isolated

Set this attribute to a boolean value to indicate whether cached instances should be in the shared cache or in a client isolated cache (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowadv.htm#CACCGBHG">Isolated Client Session Cache</a>").

false

optional


expiry

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

-1 (no expiry)

optional


expiryTimeOfDay

Set this attribute to a specific time of day (oracle.toplink.annotations.TimeOfDay) when the cached instance will expire. Queries executed against the cache after this will be forced back to the database for a refreshed copy.

@TimeOfDay(specified=false)

optional


alwaysRefresh

Set this attribute to a boolean value of true to force all queries that go to the database to always refresh the cache.

false

optional


refreshOnlyIfNewer

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

Note: this option only applies if one of the other refreshing options, such as alwaysRefresh, is already enabled.

Note: a version field is necessary to apply this feature.

For more information, see the following:

false

optional


disableHits

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

false

optional


coordinationType

Set this attribute to the cache coordination mode (oracle.toplink.annotations.CacheCoordinationType enumerated type).

The following are the valid values for the CacheCoordinationType:

  • SEND_OBJECT_CHANGES–This option sends a list of changed objects (including information about the changes). This data is merged into the receiving cache.

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

  • SEND_NEW_OBJECTS_WITH_CHANGES–This option is similar to SEND_OBJECT_CHANGES except it also includes any newly created objects from the transaction.

  • NONE–This option does not coordinate cache.

For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/cachun.htm#CHEDFBFB">Understanding Cache Coordination</a>".

CacheCoordinationType.SEND_OBJECT_CHANGES

optional




<tbody> </tbody>

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.

<a id="BABIHGBG" name="BABIHGBG"></a>

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 id="sthref11" name="sthref11"></a><a id="CJAFFDEG" name="CJAFFDEG"></a>

Table 1-10 TopLink JPA Properties for Caching

<thead> </thead> <tbody> </tbody>
Property Usage Default
<a id="toplink.cache.type.default" name="toplink.cache.type.default"></a>

<a id="CACCAEFH" name="CACCAEFH"></a>toplink.cache.type.default

The default type of session cache.

A session cache is a shared cache that services clients attached to a given session. When you read objects from or write objects to the data source using a client session, 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 EntityManagerFactory wraps an oracle.toplink.threetier.ServerSession; entity managers wrap an oracle.toplink.sessions.UnitOfWork and oracle.toplink.threetier.ClientSession. For more information about sessions, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/sesun.htm#CACJAFDF">Understanding TopLink Sessions</a>".

The following are the valid values for the oracle.toplink.config.CacheType:

Note: the values are case-sensitive.

Note: using this property, you can override the @Cache annotation (see <a href="#BABFCJJB">"How to Use the @Cache Annotation"</a>) attribute <a href="#CACDJFCF">type</a>.

Example: persistence.xml file

<property name="toplink.cache.type.default" value="Full"/>

Example: property Map

import oracle.toplink.config.CacheType;
import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.CACHE_TYPE_DEFAULT, CacheType.Full);

CacheType.SoftWeak

<a id="toplink.cache.size.default" name="toplink.cache.size.default"></a>

toplink.cache.size.default

The default maximum number of objects allowed in a TopLink cache.

Valid values: 0 to Integer.MAX_VALUE as a String.

Example: persistence.xml file

<property name="toplink.cache.size.default" value="5000"/>

Example: property Map

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>

toplink.cache.shared.default

The default for whether or not the TopLink session cache is shared by multiple client sessions.

The following are the valid values:

  • true–The session cache services all clients attached to the 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 all other processes in the session.

  • false–The session cache services a single, isolated client exclusively. The isolated client can reference objects in a shared session cache but no client can reference objects in the isolated client's exclusive cache.

Example: persistence.xml file


<property name="toplink.cache.shared.default" value="true"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.CACHE_SHARED_DEFAULT, "true");

true

<a id="toplink.cache.type.ENTITY" name="toplink.cache.type.ENTITY"></a>

<a id="CACGFGJE" name="CACGFGJE"></a>toplink.cache.type.<ENTITY>

The type of session cache for the JPA entity named <ENTITY> or with the class name <ENTITY>.

For more information on entity names, see Section 8.1 "Entity" of the JPA specification.

The following are the valid values for the oracle.toplink.config.CacheType:

  • Full–see <a href="#CACCAEFH">toplink.cache.type.default</a>

  • HardWeak–see <a href="#CACCAEFH">toplink.cache.type.default</a>

  • NONE–see <a href="#CACCAEFH">toplink.cache.type.default</a>

  • SoftWeak–see <a href="#CACCAEFH">toplink.cache.type.default</a>

  • Weak–see <a href="#CACCAEFH">toplink.cache.type.default</a>

Note: using this property, you can override the @Cache annotation (see <a href="#BABFCJJB">"How to Use the @Cache Annotation"</a>) attribute <a href="#CACDJFCF">type</a>.

Example: persistence.xml file

<property name="toplink.cache.type.Order" value="Full"/>

Example: property Map

import oracle.toplink.config.CacheType;
import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.CACHE_TYPE+".Order", CacheType.Full);

CacheType.SoftWeak

<a id="toplink.cache.size.ENTITY" name="toplink.cache.size.ENTITY"></a>

toplink.cache.size.<ENTITY>

The maximum number of JPA entities of the type denoted by JPA entity name <ENTITY> allowed in a TopLink cache.

For more information on entity names, see Section 8.1 "Entity" of the JPA specification.

Valid values: 0 to Integer.MAX_VALUE as a String.

Example: persistence.xml file

<property name="toplink.cache.size.Order" value="5000"/>

Example: property Map

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>

toplink.cache.shared.<ENTITY>

Whether or not the TopLink session cache is shared by multiple client sessions for JPA entities of the type denoted by JPA entity name <ENTITY>.

For more information on entity names, see Section 8.1 "Entity" of the JPA specification.

The following are the valid values:

  • true–The session cache services all clients attached to the 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 all other processes in the session.

  • false–The session cache services a single, isolated client exclusively. The isolated client can reference objects in a shared session cache but no client can reference objects in the isolated client's exclusive cache.

Example: persistence.xml file

<property name="toplink.cache.shared.Order" value="true"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.CACHE_SHARED+".Order", "true");

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.

<a id="sthref12" name="sthref12"></a><a id="BABEJDEB" name="BABEJDEB"></a>

Table 1-11 Attributes of the @TimeOfDay Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

hour

Set this attribute to the int value representing an hour of the day.

0

optional

minute

Set this attribute to the int value representing a minute of the day.

0

optional

second

Set this attribute to the int value representing a second of the day.

0

optional

millisecond

Set this attribute to the int value representing a millisecond of the day.

0

optional


<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.


<tbody> </tbody>

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).


<tbody> </tbody>

Note:

A @Customizer is not inherited from its parent classes.

<a href="#BABFBIEA">Table 1-12</a> lists attributes of the @Customizer annotation.

<a id="sthref13" name="sthref13"></a><a id="BABFBIEA" name="BABFBIEA"></a>

Table 1-12 Attributes of the @Customizer Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

value

Set this attribute to the Class of the descriptor customizer that you want to apply to your entity's descriptor.

no default

required


<a href="#BABIGIAH">Example 1-10</a> shows how to use the @Customizer annotation.

<a id="BABIGIAH" name="BABIGIAH"></a>

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.

<a id="sthref14" name="sthref14"></a><a id="CJADHEEB" name="CJADHEEB"></a>

Table 1-13 TopLink JPA Persistence Unit Properties for Customization and Validation

<thead> </thead> <tbody> </tbody>
Property Usage Default
<a id="toplink.orm.throw.exceptions" name="toplink.orm.throw.exceptions"></a>

toplink.orm.throw.exceptions

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 persistence.xml file <mapping-file> element.

The following are the valid values:

  • true–throw exceptions.

  • false–log warning only.

Example: persistence.xml file

<property name="oracle.orm.throw.exceptions" value="false"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.TOPLINK_ORM_THROW_EXCEPTIONS, "false");

true

<a id="toplink.weaving" name="toplink.weaving"></a>

<a id="CJAFECEI" name="CJAFECEI"></a>toplink.weaving

Control whether or not the weaving of the entity classes is performed. Weaving is required in order to use lazy fetching of @OneToOne (see Section 9.1.23 "OneToOne Annotation" of the JPA specification) and @ManyToOne (see Section 9.1.22 "ManyToOne Annotation" of the JPA specification) relationships.

The following are the valid values:

  • true–weave entity classes.

  • false–do not weave entity classes.

  • static–weave entity classes statically.

    Use this option if you plan to execute your application outside of a Java EE 5 container in an environment that does not permit the use of -javaagent:toplink-agent.jar on the JVM command line.

    This assumes that classes have already been statically woven. Run the Static weaver tool on the classes before deploying them.

    For more information on static weaving, see <a href="#StaticWeaving">"How to Configure Static Weaving Using the StaticWeave Class on the Command Line"</a> and <a href="#CJAGHHFH">"How to Use Static Weaving with the weave Ant Task"</a>.

For more information, including the option of using the TopLink JPA weave Ant task, see <a href="#CACEDCAF">"Using TopLink JPA Lazy Loading"</a>.

Example: persistence.xml file

<property name="toplink.weaving" value="false"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.WEAVING, "false");

true

toplink.weaving.lazy

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:

  • true–enable lazy one-to-one mapping through weaving.

  • false–disable lazy one-to-one mapping through weaving.

Note: you may set this option only if the <a href="#CJAFECEI">toplink.weaving</a> option is set to true. The purpose of the toplink.weaving.lazy option is to provide more granular control over weaving.

For more information, see <a href="#CACEDCAF">"Using TopLink JPA Lazy Loading"</a>.

Example: persistence.xml file

<property name="toplink.weaving.lazy" value="false"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.WEAVING_LAZY, "false");

true

toplink.weaving.changetracking

Enable or disable the AttributeLevelChangeTracking through weaving.

The following are the valid values:

  • true–enable the AttributeLevelChangeTracking through weaving. When enabled, only classes with all mappings allowing change tracking have change tracking enabled.

  • false–disable the AttributeLevelChangeTracking through weaving. Use this setting if the following applies:

    - you cannot weave at all;

    - you do not want your classes to be changed during weaving (for example, for debugging purposes);

    - you wish to disable this feature for configurations that do not support it (for example, you are mutating the java.util.Date or java.util.Calendar, you are using property access but modifying the underlying instance variables).

Note: you may set this option only if the <a href="#CJAFECEI">toplink.weaving</a> option is set to true. The purpose of the toplink.weaving.lazy option is to provide more granular control over weaving.

For more information, see <a href="#CACEDCAF">"Using TopLink JPA Lazy Loading"</a>.

Example: persistence.xml file

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

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.WEAVING_CHANGE_TRACKING, "false");

true

<a id="toplink.session.customizer" name="toplink.session.customizer"></a>

toplink.session.customizer

Specify a TopLink session customizer class: a Java class that implements the oracle.toplink.tools.sessionconfiguration.SessionCustomizer interface and provides a default (zero-argument) constructor. Use this class' customize method, which takes an oracle.toplink.sessions.Session, to programmatically access advanced TopLink session API.

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 SessionCustomizer class fully qualified by its package name.

Example: persistence.xml file

<property name="toplink.session.customizer" value="acme.sessions.MySessionCustomizer"/>

Example: property Map

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>toplink.descriptor.customizer.<ENTITY>

Specify a TopLink descriptor customizer class–a Java class that implements the oracle.toplink.tools.sessionconfiguration.DescriptorCustomizer interface and provides a default (zero-argument) constructor. Use this class's customize method, which takes an oracle.toplink.descriptors.ClassDescriptor, to programmatically access advanced TopLink descriptor and mapping API for the descriptor associated with the JPA entity named <ENTITY>.

For more information on entity names, see Section 8.1 "Entity" of the JPA specification

For more information on TopLink descriptors, see the following:

Note: TopLink does not support multiple descriptor customizers.

Valid values: class name of a DescriptorCustomizer class fully qualified by its package name.

Example: persistence.xml file

<property name="toplink.descriptor.customizer.Order" value="acme.sessions.MyDescriptorCustomizer"/>

Example: property Map

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>").


<tbody> </tbody>

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.

<a id="BABGIGFG" name="BABGIGFG"></a>

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.

<a id="sthref15" name="sthref15"></a><a id="BABIAAEG" name="BABIAAEG"></a>

Table 1-14 Attributes of the @ReturnInsert Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

returnOnly

Set this attribute to the boolean value of true if you want a return of a value for this field, without including the field in the insert.

false

optional


<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.

<a id="BABBBHIH" name="BABBBHIH"></a>

Example 1-12 Usage of the @ReturnInsert Annotation Without Arguments

@ReturnInsert
public String getFirstName() {
    return firstName;
}
<a id="BABEHAHA" name="BABEHAHA"></a>

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.

<a id="BABGGADH" name="BABGGADH"></a>

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 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.


<tbody> </tbody>

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.

<a id="sthref16" name="sthref16"></a><a id="BABGIDIC" name="BABGIDIC"></a>

Table 1-15 Attributes of the @OptimisticLocking Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

type

Set this attribute to the type (oracle.toplink.annotations.OptimisticLockingType enumerated type) of the optimistic locking policy that you will be using.

The following are the valid values for the OptimisticLockingType:

  • ALL_COLUMNS–Use this type of locking policy to compare every field in the table in the WHERE clause during an update or a delete operation. If any field has been changed, TopLink will throw an optimistic locking exception.

  • CHANGED_COLUMNS–Use this type of locking policy to compare changed fields in the table in the WHERE clause during an update operation. If any field has been changed, TopLink will throw an optimistic locking exception.

    Note: performing the same during a delete operation will only compare primary keys.

  • <a id="CJAHGDGE" name="CJAHGDGE"></a>SELECTED_COLUMNS–Use this type of locking policy to compare selected fields in the table in the WHERE clause during an update or a delete operation. If any field has been changed, TopLink will throw an optimistic locking exception.

    Note: specified fields must be mapped and must not be primary keys.

    Note: TopLink will throw an exception if you set the SELECTED_COLUMNS type, but fail to specify the selectedColumns. You must also specify the name attribute of Column.

  • <a id="CJACFHAD" name="CJACFHAD"></a>VERSION_COLUMN–Use this type of locking policy to compare a single version number in the WHERE clause during an update operation in each @Column annotaion.

    Note: the version field must be mapped and must not be the primary key.

    Note: this functionality is equivalent to the functionality of the @Version annotation (see Section 9.1.17 "Version Annotation" of the JPA specification) in JPA.

    For more information, see <a href="#CJAEHCDC">"What You May Need to Know About Version Fields"</a>.

OptimisticLockingType.VERSION_COLUMN

optional

selectedColumns

Set this attribute to an array of javax.persistence.Column instances.

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 selectedColumns. You must also specify the name attribute of Column.

empty Column array

optional

cascade

Set the value of this attribute to a boolean value of true to specify that the optimistic locking policy should cascade the lock.

By enabling cascading you configure 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:

false

optional



<tbody> </tbody>

Note:

Setting an @OptimisticLocking may override any @Version specification (see Section 9.1.17 "Version Annotation" of the JPA specification) on the entity: TopLink will not throw an exception, but will log a warning.

You can specify @Version without any @OptimisticLocking specification to define a version locking policy (oracle.toplink.descriptors.VersionLockingPolicy) on the source entity..


<a href="#BABCDJHJ">Example 1-15</a> shows how to use the @OptimisticLocking annotation with the ALL_COLUMNS type.

<a id="BABCDJHJ" name="BABCDJHJ"></a>

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.

<a id="BABGABBB" name="BABGABBB"></a>

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.

<a id="BABBCHDH" name="BABBCHDH"></a>

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.

<a id="BABBAIGH" name="BABBAIGH"></a>

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.

<a id="sthref17" name="sthref17"></a><a id="BABHCIJD" name="BABHCIJD"></a>

Table 1-16 Attributes of the @NamedStoredProcedureQuery Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

name

Set this attribute to the unique String name that references this stored procedure query.

no default

required

hints

Set this attribute to an array of javax.persistence.QueryHint instances.

empty QueryHint array

optional

resultClass

Set this attribute to the Class of the query result.

void.class

optional

resultSetMapping

Set this attribute to the String name of the javax.persistence.SQLResultSetMapping instance.

empty String

optional

procedureName

Set this attribute to the String name of the stored procedure.

no default

required

returnsResultSet

Set this attribute to the boolean value of false to disable the return of the result set.

true

optional

procedureParameters

Set the value of this attribute to an array of oracle.toplink.annotations.StoredProcedureParameter instances to define arguments to the stored procedure.

The following are attributes of the StoredProcedureParameter:

  • procedureParameterDirection–Set the value of this attribute to define the direction (oracle.toplink.annotations.Direction enumerated type) of the stored procedure parameter.

    The default value is an empty Direction.IN.

    The following are valid values for Direction.IN:

    - IN–Input parameter

    - OUT–Output parameter

    - IN_OUT–Input and output parameter

    - OUT_CURSOR–Output cursor

    You are not required to set the value of this attribute.

    Note: TopLink will throw an exception if you set more than one parameter to the OUT_CURSOR type.

  • name–Set this attribute to the String name of the stored procedure parameter.

    The default value is an empty String.

    You are not required to set the value of this attribute.

  • queryParameter–Set this attribute to the String name of the query parameter.

    You are required to set the value of this attribute.

  • type–Set this attribute to the type of Java Class that you want to receive back from the procedure. This depends on the type returned from the procedure.

    The default value is void.class.

    You are not required to set the value of this attribute.

  • jdbcType–Set this attribute to the int value of JDBC type code. This depends on the type returned from the procedure.

    The default value is -1.

    You are not required to set the value of this attribute.

  • jdbcTypeName–Set this attribute to the String value of the JDBC type name.

    The default value is an empty String.

    You are not required to set the value of this attribute.

    Note: Setting of this attribute may be required for ARRAY or STRUCT types.

For more information, see the following:

empty StoredProcedureParameter array

optional


<a href="#BABCFFIJ">Example 1-19</a> shows how to use the @NamedStoredProcedureQuery annotation.

<a id="BABCFFIJ" name="BABCFFIJ"></a>

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.

<a id="sthref18" name="sthref18"></a><a id="BABCECFE" name="BABCECFE"></a>

Table 1-17 Attributes of the @NamedStoredProcedureQueries Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

value

Set this attribute to the array of @NamedStoredProcedureQuery.

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.

<a id="sthref19" name="sthref19"></a><a id="CJAJGAEC" name="CJAJGAEC"></a>

Table 1-18 TopLink JPA Persistence Unit Properties for JDBC Connection Communication

<thead> </thead> <tbody> </tbody>
Property Usage Default
<a id="toplink.jdbc.bind-parameters_persistence.xml" name="toplink.jdbc.bind-parameters_persistence.xml"></a>

toplink.jdbc.bind-parameters

Control whether or not the query uses parameter binding.

Note: this property applies when used in a Java SE environment.

For more information, see "<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:

  • true–bind all parameters.

  • false–do not bind parameters.

Example: persistence.xml file

<property name="toplink.jdbc.bind-parameters" value="false"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_BIND_PARAMETERS, "false");

true

toplink.jdbc.native-sql

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:

  • true–enable TopLink's generation of database platform-specific SQL.

  • false–disable generation of database platform-specific SQL by TopLink.

Example: persistence.xml file

<property name="toplink.jdbc.native-sql" value="true"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.NATIVE_SQL, "true");

false

toplink.jdbc.batch-writing

Specify the use of batch writing to optimize transactions with multiple write operations.

Set the value of this property into the session at deployment time.

Note: This property applies when used both in a Java SE and Java EE environment.

The following are the valid values:

  • JDBC–use JDBC batch writing instead of native platform batch writing.

  • BUFFERED–do not use either JDBC batch writing nor native platform batch writing.

  • ORACLE_JDBC–use both JDBC batch writing and native platform batch writing.

  • NONE–do not use batch writing (turn it off).

Note: if you set any other value, TopLink will throw an exception.

Example: persistence.xml file

<property name="toplink.jdbc.batch-writing" value="BUFFERED"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.BATCH_WRITING, "BUFFERED");

NONE

toplink.jdbc.cache-statements.size

The number of statements held when using internal statement caching.

Set the value at the deployment time.

Note: this property applies when used both in a Java SE and Java EE environment.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

Example: persistence.xml file

<property name="toplink.jdbc.cache-statements.size" value="2"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.CACHE_STATEMENTS_SIZE, "2");

50

<a id="toplink.jdbc.driver" name="toplink.jdbc.driver"></a>

toplink.jdbc.driver

The class name of the JDBC driver you want to use, fully qualified by its package name. This class must be on your application classpath.

Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ).

Example: persistence.xml file

<property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver");

<a id="toplink.jdbc.password" name="toplink.jdbc.password"></a>

toplink.jdbc.password

The password for your JDBC user.

Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification ).

Example: persistence.xml file

<property name="toplink.jdbc.password" value="tiger"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_PASSWORD, "tiger");

<a id="toplink.jdbc.url" name="toplink.jdbc.url"></a>

toplink.jdbc.url

The JDBC connection URL required by your JDBC driver.

Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification )

Example: persistence.xml file

<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@MYHOST:1521:MYSID"/>

Example: property Map

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>

toplink.jdbc.user

The user name for your JDBC user.

Note: this property applies when used in a Java SE environment or a resource-local persistence unit (see Section 5.5.2 "Resource-Local Entity Managers" and Section 6.2.1.2 "transaction-type" of the JPA specification )

Example: persistence.xml file

<property name="toplink.jdbc.url" value="scott"/>

Example: property Map

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>").

<a id="sthref20" name="sthref20"></a><a id="CJACCJFI" name="CJACCJFI"></a>

Table 1-19 TopLink JPA Persistence Unit Properties for JDBC Connection Pooling

<thead> </thead> <tbody> </tbody>
Property Usage Default

toplink.jdbc.read-connections.max

The maximum number of connections allowed in the JDBC read connection pool.

Note: this property applies when used in a Java SE environment.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

Example: persistence.xml file

<property name="toplink.jdbc.read-connections.max" value="3"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_MAX, "3");

2

toplink.jdbc.read-connections.min

The minimum number of connections allowed in the JDBC read connection pool.

Note: this property applies when used in a Java SE environment.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

Example: persistence.xml file

<property name="toplink.jdbc.read-connections.min" value="1"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_MIN, "1");

2

toplink.jdbc.read-connections.shared

Specify whether or not to allow concurrent use of shared read connections.

Note: this property applies when used in a Java SE environment.

The following are the valid values:

  • true–allow concurrent use of shared read connections.

  • false–do not allow the concurrent use of shared read connections; concurrent readers are each allocated their own read connection.

Example: persistence.xml file

<property name="toplink.jdbc.read-connections.shared" value="true"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_READ_CONNECTIONS_SHARED, "true");

false

toplink.jdbc.write-connections.max

The maximum number of connections allowed in the JDBC write connection pool.

Note: this property applies when used in a Java SE environment.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

Example: persistence.xml file

<property name="toplink.jdbc.write-connections.max" value="5"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(ToplinkProperties.JDBC_WRITE_CONNECTIONS_MAX, "5");

10

toplink.jdbc.write-connections.min

The maximum number of connections allowed in the JDBC write connection pool.

Note: this property applies when used in a Java SE environment.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

Example: persistence.xml file

<property name="toplink.jdbc.write-connections.min" value="2"/>

Example: property Map

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>".

<a id="sthref21" name="sthref21"></a><a id="CJAHJIJH" name="CJAHJIJH"></a>

Table 1-20 TopLink JPA Persistence Unit Properties for Logging

<thead> </thead> <tbody> </tbody>
Property Usage Default

toplink.logging.logger

Select the type of logger to use:

The following are the valid values:

  • DefaultLogger–the TopLink native logger oracle.toplink.logging.DefaultSessionLog.

  • JavaLogger–the java.util.logging logger oracle.toplink.logging.JavaLog.

  • Fully qualified class name of a custom logger. The custom logger must implement the oracle.toplink.logging.SessionLog interface.

Example: persistence.xml file

<property name="toplink.logging.logger" value="acme.loggers.MyCustomLogger" />

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_LOGGER, "acme.loggers.MyCustomLogger" />

DefaultLogger

<a id="toplink.logging.level" name="toplink.logging.level"></a>

toplink.logging.level

Control the amount and detail of log output by configuring the log level (in ascending order of information):

The following are the valid values for the java.util.logging.Level:

  • 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.

Example: persistence.xml file

<property name="toplink.logging.level" value="INFO"/>

Example: property Map

import java.util.logging.Level;
import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_LEVEL, Level.INFO);

CONFIG

<a id="toplink.logging.timestamp" name="toplink.logging.timestamp"></a>

toplink.logging.timestamp

Control whether the timestamp is logged in each log entry.

The following are the valid values:

  • true–log a timestamp.

  • false–do not log a timestamp.

Example: persistence.xml file

<property name="toplink.logging.timestamp" value="false"/>

Example: property Map


import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_TIMESTAMP, "false");

true

<a id="toplink.logging.thread" name="toplink.logging.thread"></a>

toplink.logging.thread

Control whether a thread identifier is logged in each log entry.

The following are the valid values:

  • true–log a thread identifier.

  • false–do not log a thread identifier.

Example: persistence.xml file

<property name="toplink.logging.thread" value="false"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_THREAD, "false");

true

<a id="toplink.logging.session" name="toplink.logging.session"></a>

toplink.logging.session

Control whether a TopLink session identifier is logged in each log entry.

The following are the valid values:

  • true–log a TopLink session identifier.

  • false–do not log a TopLink session identifier.

Example: persistence.xml file

<property name="toplink.logging.session" value="false"/>

Example: property Map


import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_SESSION, "false");

true

<a id="toplink.logging.exceptions" name="toplink.logging.exceptions"></a>

toplink.logging.exceptions

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:

  • true–log all exceptions.

  • false–do not log exceptions.

Example: persistence.xml file

<property name="toplink.logging.exceptions" value="true"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.LOGGING_EXCEPTIONS, "true");

false

toplink.logging.file

Specify a file location for the log output (instead of the standard out).

Note: this property applies when used in a Java SE environment.

Valid values: a string location to a directory in which you have write access. The location may be relative to your current working directory or absolute.

Example: persistence.xml file

<property name="toplink.logging.file" value="C:\myout\"/>

Example: property Map

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.

<a id="sthref22" name="sthref22"></a><a id="CJAEBIJC" name="CJAEBIJC"></a>

Table 1-21 TopLink JPA Persistence Unit Properties for Database, Session, and Application Server

<thead> </thead> <tbody> </tbody>
Property Usage Default
<a id="toplink.session-name" name="toplink.session-name"></a>

toplink.session-name

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 sessions.xml file

Valid values: a valid TopLink session name that is unique in a server deployment.

Example: persistence.xml file

<property name="toplink.session-name" value="MySession"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.SESSION_NAME, "MySession");

TopLink generated unique name.

<a id="CJACBJGJ" name="CJACBJGJ"></a>toplink.session-xml

Specify persistence information loaded from the TopLink session configuration file (sessions.xml).

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 persistence.xml, as well as ORM.xml and other mapping files, if present. For more information, see <a href="#CJABFEFC">"Overriding Annotations in TopLink JPA"</a>.

Indicate the session by setting the toplink.session-name property.

Note: if you do not specify the value for this property, sessions.xml file will not be used.

Valid values: the resource name of the sessions XML file.

Example: persistence.xml file

<property name="toplink.session-xml" value="mysession.xml"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.SESSION_XML, "mysession.xml");

toplink.session-event-listener

Specify a descriptor event listener to be added during bootstrapping.

Valid values: qualified class name for a class that implements the oracle.toplink.sessions.SessionEventListener interface.

Example: persistence.xml file

<property name="toplink.session-event-listener" value="mypackage.MyClass.class"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.SESSION_EVENT_LISTENER_CLASS, "mypackage.MyClass.class");

toplink.session.include.descriptor.queries

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:

  • true–enable the default copying of all named queries from the descriptors to the session.

  • false–disable the default copying of all named queries from the descriptors to the session.

Example: persistence.xml file

<property name="toplink.session.include.descriptor.queries" value="false"/>

Example: property Map

import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.INCLUDE_DESCRIPTOR_QUERIES, "false");

true

<a id="toplink.target-database" name="toplink.target-database"></a>

toplink.target-database

Specify the type of database that your JPA application uses. The oracle.toplink.config.TargetDatabase enumerated type contains an entry for many of the more common database types supported.

The following are the valid values for the TargetDatabase:

  • Attunity–configure the persistence provider to use an Attunity database.

  • Auto–TopLink accesses the database and uses the metadata that JDBC provides to determine the target database. Applicable to JDBC drives that support this metadata.

  • Cloudscape–configure the persistence provider to use a Cloudscape database.

  • Database–configure the persistence provider to use a generic choice if your target database is not listed here and your JDBC driver does not support the use of metadata that the Auto option requires.

  • DB2–configure the persistence provider to use a DB2 database.

  • DB2Mainframe–configure the persistence provider to use a DB2Mainframe database.

  • DBase–configure the persistence provider to use a DBase database.

  • Derby–configure the persistence provider to use a Derby database.

  • HSQL–configure the persistence provider to use an HSQL database.

  • Informix–configure the persistence provider to use an Informix database.

  • JavaDB–configure the persistence provider to use a JavaDB database.

  • MySQL4–configure the persistence provider to use a MySQL4 database.

  • Oracle–configure the persistence provider to use an Oracle database.

  • PointBase–configure the persistence provider to use a PointBase database.

  • PostgreSQL–configure the persistence provider to use a PostgreSQL database.

  • SQLAnyWhere–configure the persistence provider to use an SQLAnyWhere database.

  • SQLServer–configure the persistence provider to use an SQLServer database.

  • Sybase–configure the persistence provider to use a Sybase database.

  • TimesTen–configure the persistence provider to use a TimesTen database.

You can also set the value to the fully qualified classname of a subclass of the oracle.toplink.platform.DatabasePlatform class.

Example: persistence.xml file

<property name="toplink.target-database" value="Oracle"/>

Example: property Map

import oracle.toplink.config.TargetDatabase;
import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.TARGET_DATABASE, TargetDatabase.Oracle);

TargetDatabase.Auto

<a id="toplink.target-server" name="toplink.target-server"></a>

toplink.target-server

Specify the type of application server that your JPA application uses:

The following are the valid values for the oracle.toplink.config.TargetServer:

  • None–configure the persistence provider to use no application server.

  • OC4J_10_1_3–configure the persistence provider to use OC4J 10.1.3.0.

    Note: this server sets this property automatically, so you do not need to set it, unless it is disabled.

  • SunAS9–configure the persistence provider to use Sun Application Server version 9.

    Note: this server sets this property automatically, so you do not need to set it, unless it is disabled.

Example: persistence.xml file

<property name="toplink.target-server" value="OC4J_10_1_3"/>

Example: property Map

import oracle.toplink.config.TargetServer;
import oracle.toplink.config.TopLinkProperties;
propertiesMap.put(TopLinkProperties.TARGET_SERVER, TargetServer.OC4J_10_1_3);

None


For information about the configuration of platforms, see the following:

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.

<a id="sthref23" name="sthref23"></a><a id="CJAJIIIA" name="CJAJIIIA"></a>

Table 1-22 TopLink JPA Persistence Unit Properties for Schema Generation

<thead> </thead> <tbody> </tbody>
Property Usage Default
<a id="toplink.ddl-generation" name="toplink.ddl-generation"></a>

<a id="CJAGHFGI" name="CJAGHFGI"></a>toplink.ddl-generation

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 oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider:

  • none–do not generate DDL; no schema is generated.

  • create-tables–create DDL for non-existent tables; leave existing tables unchanged (see also <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a>).

  • drop-and-create-tables–create DDL for all tables; drop all existing tables (see also <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> and <a href="#CJAEEFBE">toplink.drop-ddl-jdbc-file-name</a>).

If you are using persistence in a Java SE environment and would like to create the DDL files without creating tables, additionally define a Java system property INTERACT_WITH_DB and set its value to false.

Example: persistence.xml file

<property name="toplink.ddl-generation" value="create-tables"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.DDL_GENERATION, EntityManagerFactoryProvider.CREATE_ONLY);

none

<a id="toplink.application-location" name="toplink.application-location"></a>

<a id="CJAFGEBH" name="CJAFGEBH"></a>toplink.application-location

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 none.

Valid values: a file specification to a directory in which you have write access. The file specification may be relative to your current working directory or absolute. If it does not end in a file separator, TopLink will append one valid for your operating system.

Example: persistence.xml file

<property name="toplink.application-location" value="C:\ddl\"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.APP_LOCATION, "C:\ddl\");

"."+File.separator

<a id="toplink.create-ddl-jdbc-file-name" name="toplink.create-ddl-jdbc-file-name"></a>

<a id="CJAIIDIB" name="CJAIIDIB"></a>toplink.create-ddl-jdbc-file-name

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 create-tables or drop-and-create-tables.

Valid values: a file name valid for your operating system. Optionally, you may prefix the file name with a file path as long as the concatenation of <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: persistence.xml file

<property name="toplink.create-ddl-jdbc-file-name" value="create.sql"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.CREATE_JDBC_DDL_FILE, "create.sql");

createDDL.jdbc

<a id="toplink.drop-ddl-jdbc-file-name" name="toplink.drop-ddl-jdbc-file-name"></a>

<a id="CJAEEFBE" name="CJAEEFBE"></a>toplink.drop-ddl-jdbc-file-name

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 drop-and-create-tables

Valid values: a file name valid for your operating system. Optionally, you may prefix the file name with a file path as long as the concatenation of <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: persistence.xml file

<property name="toplink.drop-ddl-jdbc-file-name" value="drop.sql"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.DROP_JDBC_DDL_FILE, "drop.sql");

dropDDL.jdbc

<a id="toplink.ddl-generation.output-mode" name="toplink.ddl-generation.output-mode"></a>

<a id="CJAHICAC" name="CJAHICAC"></a>toplink.ddl-generation.output-mode

Use this property to specify the DDL generation target.

The following are the valid values for the oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider:

  • both–generate SQL files and execute them on the database.

    If <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to create-tables, then <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> is written to <a href="#CJAFGEBH">toplink.application-location</a> and executed on the database.

    If <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to drop-and-create-tables, then both <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> and <a href="#CJAEEFBE">toplink.drop-ddl-jdbc-file-name</a> are written to <a href="#CJAFGEBH">toplink.application-location</a> and both SQL files are executed on the database.

  • database–execute SQL on the database only (do not generate SQL files).

  • sql-script–generate SQL files only (do not execute them on the database).

    If <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to create-tables, then <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> is written to <a href="#CJAFGEBH">toplink.application-location</a>. It is not executed on the database.

    If <a href="#CJAGHFGI">toplink.ddl-generation</a> is set to drop-and-create-tables, then both <a href="#CJAIIDIB">toplink.create-ddl-jdbc-file-name</a> and <a href="#CJAEEFBE">toplink.drop-ddl-jdbc-file-name</a> are written to <a href="#CJAFGEBH">toplink.application-location</a>. Neither is executed on the database.

Example: persistence.xml file

<property name="toplink.ddl-generation.output-mode" value="database"/>

Example: property Map

import oracle.toplink.ejb.cmp3.EntityManagerFactoryProvider;
propertiesMap.put(EntityManagerFactoryProvider.DDL_GENERATION_MODE, EntityManagerFactoryProvider.DDL_DATABASE_GENERATION);

Container or Java EE mode: EntityManagerFactoryProvider.sql-script

Bootstrap or Java SE mode: EntityManagerFactoryProvider.both


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 { ... }

<tbody> </tbody>

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.

<a id="sthref24" name="sthref24"></a><a id="BABCBEBA" name="BABCBEBA"></a>

Table 1-23 Attributes of the @ChangeTracking Annotation

<thead> </thead> <tbody> </tbody>
Attribute Description Default Required or Optional

value

Set this attribute to the type of the change tracking (oracle.toplink.annotations.ChangeTrackingType enumerated type) to use.

The following are the valid values for the ChangeTrackingType:

  • ATTRIBUTE–This option allows change tracking at the attribute level of an object. Objects with changed attributes will be processed at the commit time to include any changes in the results of the commit. Unchanged objects will be ignored.

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowund.htm#CIHBBGBB">Attribute Change Tracking Policy</a>".

  • OBJECT–This option allows an object to calculate for itself whether or not it has changed. Changed objects will be processed at the commit time to include any changes in the results of the commit. Unchanged objects will be ignored.

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowund.htm#CIHDJFIC">Object-Level Change Tracking Policy</a>".

  • DEFERRED–This option defers all change detection to the UnitOfWork's change detection process.

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowund.htm#CIHBIEDF">Deferred Change Tracking Policy</a>".

  • AUTO–This option does not set any change tracking policy. The policy is determined by the TopLink agent: if the class can be weaved for change tracking the ATTRIBUTE option is used; otherwise, the DEFERRED option is used.

ChangeTrackingType.AUTO

optional


<a href="#BABJHDGJ">Example 1-20</a> shows how to use the @ChangeTracking annotation.

<a id="BABJHDGJ" name="BABJHDGJ"></a>

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.

<a id="CJAGAFIC" name="CJAGAFIC"></a>

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();
<a id="CJADBIHF" name="CJADBIHF"></a>

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 {
    ...
}
<a id="sthref25" name="sthref25"></a><a id="CJADBHCE" name="CJADBHCE"></a>

Table 1-24 TopLink JPA Query Hints

<thead> </thead> <tbody> </tbody>
Hint Usage Default

toplink.cache-usage

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 oracle.toplink.config.CacheUsage:

  • DoNotCheckCache–Always go to the database.

  • CheckCacheByExactPrimaryKey–If a read-object query contains an expression where the primary key is the only comparison, you can obtain a cache hit if you process the expression against the object in memory

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qrybas.htm#BCFCEAJG">Reading Objects Using Query-By-Example</a>".

  • CheckCacheByPrimaryKey–If a read-object query contains an expression that compares at least the primary key, you can obtain a cache hit if you process the expression against the objects in memory.

  • CheckCacheThenDatabase–You can configure any read-object query to check the cache completely before you resort to accessing the database.

  • CheckCacheOnly–You can configure any read-all query to check only the parent session cache (shared cache) and return the result from it without accessing the database.

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/qrybas.htm#BCFCEAJG">Reading Objects Using Query-By-Example</a>".

  • ConformResultsInUnitOfWork–You can configure any read-object or read-all query within the context of a unit of work to conform the results with the changes to the object made within that unit of work. This includes new objects, deleted objects and changed objects.

    For more information, see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowadv.htm#CACIJJBF">Using Conforming Queries and Descriptors</a>".

  • UseEntityDefault–Use the cache configuration as specified by the TopLink descriptor API for this entity.

Note: the default value is related to the value that you defined in the descriptor for the disableCacheHits method (see "<a href="http://download.oracle.com/docs/cd/B32110_01/web.1013/b28218/uowadv.htm#CACEDDEC">Descriptor Method disableCacheHits</a>"), which defaults to false in the descriptor. This amounts to CheckCacheByPrimaryKey value by default, but how TopLink interprets this depends on the query: if disableCacheHits were set to true, DoNotCheckCache would be the default. For a read-all query, CheckCacheByPrimaryKey means the same as DoNotCheckCache. For a read-object query, this means the cache is first checked for a primary key query. For a report query, toplink.cache-usage hint is not supported. Currently, in TopLink JPA read-all queries are used for any "simple" queries, and report queries are used for "complex" queries (for example, selecting non-objects or multiple objects); read-object queries are never used making the toplink.cache-usage somewhat limited.

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: @QueryHint

import oracle.toplink.config.CacheUsage;
import oracle.toplink.config.TargetDatabase;
@QueryHint(name=TopLinkQueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheOnly);

CacheUsage.UseEntityDefault

<a id="toplink.jdbc.bind-parameters_query.hint" name="toplink.jdbc.bind-parameters_query.hint"></a>

toplink.jdbc.bind-parameters

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 oracle.toplink.config.HintValues:

Example: JPA Query API

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
query.setHint(TopLinkQueryHints.BIND_PARAMETERS, HintValues.TRUE);

Example: @QueryHint


import oracle.toplink.config.HintValues;
import oracle.toplink.config.TargetDatabase;
@QueryHint(name=TopLinkQueryHints.BIND_PARAMETERS, value=HintValues.TRUE);

HintValues.PERSISTENCE_UNIT_DEFAULT

toplink.jdbc.fetch-size

Specify the number of rows that should be fetched from the database when more rows are needed.

For large queries that return a large number of objects you can configure the row fetch size used in the query to improve performance by reducing the number database hits required to satisfy the selection criteria. Most JDBC drivers default to a fetch size of 10, so if you are reading 1000 objects, increasing the fetch size to 256 can significantly reduce the time required to fetch the query's results. The optimal fetch size is not always obvious. Usually, a fetch size of one half or one quarter of the total expected result size is optimal. Note that if you are unsure of the result set size, incorrectly setting a fetch size too large or too small can decrease performance.

A value of 0 means the JDBC driver returns results one row at a time.

Note: this property is dependent on the JDBC driver support.

Valid values: 0 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

0

toplink.jdbc.timeout

Specify the number of seconds TopLink will wait on a query before throwing a DatabaseException.

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 to Integer.MAX_VALUE (depending on your JDBC driver) as a String.

0

<a id="toplink.pessimistic-lock" name="toplink.pessimistic-lock"></a>

toplink.pessimistic-lock

Control whether or not pessimistic locking is used.

The following are the valid values for the oracle.toplink.config.PessimisticLock:

  • NoLock–pessimistic locking is not used.

  • Lock–TopLink issues a SELECT .... FOR UPDATE.

  • LockNoWait–TopLink issues a SELECT .... FOR UPDATE NO WAIT.

Example: JPA Query API

import oracle.toplink.config.PessimisticLock;
import oracle.toplink.config.TopLinkQueryHints;
query.setHint(TopLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait);

Example: @QueryHint

import oracle.toplink.config.PessimisticLock;
import oracle.toplink.config.TopLinkQueryHints;
@QueryHint(name=TopLinkQueryHints.PESSIMISTIC_LOCK, value=PessimisticLock.LockNoWait);

NoLock

toplink.batch

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 e.manager.address

Example: JPA Query API

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
query.setHint("toplink.batch", "e.address");

Example: @QueryHint

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
@QueryHint(name=TopLinkQueryHints.BATCH, value="e.address");

""

toplink.join-fetch

Allow joining of the attributes.

This is similar to toplink.batch, except that you can use it for queries that select multiple items in the SELECT clause.

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: @QueryHint


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>

toplink.refresh

Control whether or not to update the TopLink session cache with objects that the query returns.

The following are the valid values for the oracle.toplink.config.HintValues:

  • TRUE–refresh cache.

  • FALSE–do not refresh cache.

Example: JPA Query API

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
query.setHint(TopLinkQueryHints.REFRESH, HintValues.TRUE);

Example: @QueryHint

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
@QueryHint(name=TopLinkQueryHints.REFRESH, value=HintValues.TRUE);

FALSE

toplink.return-shared

Retrieve read-only results back from the query: on nontransactional read operations, where the requested entity types are stored in the shared cache, you can request that the shared instance be returned instead of a detached copy.

You must set the read-only flag for the report query to true.

Note: You should never modify objects returned from the shared cache.

The following are the valid values for the oracle.toplink.config.HintValues:

  • TRUE–retrieve read-only results back from the query;

  • FALSE–do not retrieve read-only results back from the query.

Example: JPA Query API

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
query.setHint(TopLinkQueryHints.RETURN_SHARED, HintValues.TRUE);

Example: @QueryHint

import oracle.toplink.config.HintValues;
import oracle.toplink.config.TopLinkQueryHints;
@QueryHint(name=TopLinkQueryHints.RETURN_SHARED, value=HintValues.TRUE);

FALSE

toplink.result-collection-type

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 Class that implements the Collection interface.

Note: Typically, you would execute these queries by calling the getResultsList method, which returns the java.util.List, on the Query. This means that the class specified in this hint must implement the List interface, if you are invoking it using the getResultsList method.

Note: Specify the class without the ".class" notation. For example, java.util.Vector would work, not java.util.Vector.class

TopLink will throw an exception, if you use this hint with a class that does not implement the Collection interface.

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: @QueryHint

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.

<a id="CJAFDHAG" name="CJAFDHAG"></a>

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 the Employee class looks like this:

    emp.getAddress().getStreet().equals("Meadowlands");
    
    

    The expression to get the same information is similar:

    emp.get("address").get("street").equal("Meadowlands");
    
  • Expressions allow read queries to transparently query between two classes that share a relationship. If these classes are stored in multiple tables in the database, 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.

<a id="CJAEGECE" name="CJAEGECE"></a>

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.

<a id="CJAGEAAB" name="CJAGEAAB"></a>

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.

<a id="CJAFCADG" name="CJAFCADG"></a>

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.

<a id="CJABJHIH" name="CJABJHIH"></a>

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.

<a id="CJAFCADE" name="CJAFCADE"></a>

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%".

<a id="CJAIFGEH" name="CJAIFGEH"></a>

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%".

<a id="CJAJACFB" name="CJAJACFB"></a>

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%".

<a id="CJAJJIGD" name="CJAJJIGD"></a>

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%".

<a id="CJACJIAB" name="CJACJIAB"></a>

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.

<a id="sthref26" name="sthref26"></a><a id="CJAJCGDA" name="CJAJCGDA"></a>

Table 1-25 TopLink JPA Support for Lazy Loading by Mapping Type

<thead> </thead> <tbody> </tbody>
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

@ManyToMany (see Section 9.1.26 "ManyToMany Annotation" of the JPA specification)

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (the default).

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (the default).

@OneToMany (see Section 9.1.24 "OneToMany Annotation" of the JPA specification)

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (the default).

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY (the default).

@OneToOne (see Section 9.1.23 "OneToOne Annotation" of the JPA specification)

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY.

By default, TopLink JPA ignores the fetch attribute and default javax.persistence.FetchType.EAGER applies.

To configure TopLink JPA to perform lazy loading when the fetch attribute set to FetchType.LAZY, configure one of the following:

  • Dynamic weaving (see <a href="#DynamicWeaving">"How to Configure Dynamic Weaving"</a>)

  • Static weaving with the StaticWeave class on the command line (see <a href="#StaticWeaving">"How to Configure Static Weaving Using the StaticWeave Class on the Command Line"</a>)

  • Static weaving with the weave Ant task (see <a href="#CJAGHHFH">"How to Use Static Weaving with the weave Ant Task"</a>)

@ManyToOne (see Section 9.1.22 "ManyToOne Annotation" of the JPA specification)

TopLink JPA performs lazy loading when the fetch attribute is set to javax.persistence.FetchType.LAZY.

By default, TopLink JPA ignores the fetch attribute and default javax.persistence.FetchType.EAGER applies.

To configure TopLink JPA to perform lazy loading when the fetch attribute set to FetchType.LAZY, configure one of the following:

  • Dynamic weaving (see <a href="#DynamicWeaving">"How to Configure Dynamic Weaving"</a>)

  • Static weaving with the StaticWeave class on the command line (see <a href="#StaticWeaving">"How to Configure Static Weaving Using the StaticWeave Class on the Command Line"</a>)

  • Static weaving with the weave Ant task (see <a href="#CJAGHHFH">"How to Use Static Weaving with the weave Ant Task"</a>)

@Basic (see Section 9.1.18 "Basic Annotation" of the JPA specification)

TopLink JPA ignores the fetch attribute. Default javax.persistence.FetchType.EAGER always applies.

TopLink JPA ignores the fetch attribute. Default javax.persistence.FetchType.EAGER always applies.


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 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:

  1. Configure your persistence unit with a <a href="#toplink.weaving">toplink.weaving</a> extension set to true.

  2. Modify your application JVM command line to include the following:

    -javaagent:toplink-agent.jar
    
  3. 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>).

<a id="sthref28" name="sthref28"></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:

  1. Ensure that the toplink.jar file is in your system classpath.

  2. 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> </thead> <tbody> </tbody>
    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 the persistence.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 the persistence.xml using the <a href="#CJAEFHEI">-persistenceinfo</a> attribute.


    Required

    <target>

    Specifies the output location: either a directory or a JAR file.


    Required



    <tbody> </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 the source 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:

  1. 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> </thead> <tbody> </tbody>
    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 the persistence.xml using the persistenceinfo attribute.


    Required

    target

    Specifies the output location: either a directory or a JAR file.


    Required

    persistenceinfo

    Specifies the location of the persistence.xml file if it is not in the same location as the source.


    Optional

    log

    Specifies a logging file.

    See "<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> </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 the source is a JAR file (as <a href="#CJABDJCB">Example 1-34</a> shows), TopLink JPA cannot weave in place.

  2. 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.

  3. 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 the build.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> </tbody>

    Note:

    You must specify the toplink.jar file (the JAR that contains the TopLink JPA weave Ant task) using the Ant command line -lib option instead of using the taskdef attribute classpath.

<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>).


<tbody> </tbody>

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.

<a id="CJABABHJ" name="CJABABHJ"></a>

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.

<a id="CJAEAEJH" name="CJAEAEJH"></a>

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.

<a id="sthref31" name="sthref31"></a>

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.

<a id="sthref32" name="sthref32"></a>

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.


<tbody> </tbody>

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).


<tbody> </tbody>

Note:

You can use tthe toplink.session-xml property as an alternative to annotations and deployment XML.

</body>

</html>

Back to the top