Skip Headers
Oracle® Fusion Middleware User's Guide for Oracle JDeveloper
11g Release 2 (11.1.2.3.0)

Part Number E17455-04
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

13 Developing TopLink Mappings

This chapter describes how to develop TopLink Mappings within Oracle JDeveloper. Using the TopLink Editor, you can quickly and easily configure TopLink descriptors and mappings for your Java classes, EJBs, and JPA entities to data source elements (such as database tables or XML schema elements). With the TopLink Editor, you can create this information without writing Java code.

This chapter includes the following sections which describe the general process for creating TopLink mappings and integrating them in a JDeveloper project:

For more information, see the following:

13.1 About Developing TopLink Mappings

Oracle TopLink is an advanced, object-persistence and object-transformation framework that provides development tools and run-time capabilities that reduce development and maintenance efforts, and increase enterprise application functionality.

Using the TopLink Editor available within JDeveloper you can configure and map your Java classes, EJBs, and JPA entities to different data sources, including relational databases, enterprise information systems (EIS), and XML schemas without using Java code. The TopLink Editor supports multiple standards, including JPA, JAXB, and Java EE.

TopLink links object-oriented programs with relational data structures. Using TopLink, you can build high-performance applications that store persistent object-oriented data in a relational database. TopLink successfully transforms object-oriented data into either relational data or XML documents. Using TopLink, you can integrate persistence and object-transformation into your application, while staying focused on your primary domain problem by taking advantage of an efficient, flexible, and field-proven solution.

13.1.1 Considering the Impedance Mismatch

TopLink enables you to address the disparity between Java and data sources, known as impedance mismatch. While object-relational databases consist of such elements as tables, rows, columns, and primary and foreign keys, Java and Java EE include entity classes (regular Java classes or Enterprise JavaBeans (EJB) entity beans), business rules, complex relationships, and inheritance. In a nonrelational data source, you must match your Java entities with EIS records or XML elements and schemas. These differences (as shown in Figure 13-1) are known as the object-persistence impedance mismatch.

Figure 13-1 Solving Object-Persistence Impedance Mismatch

Object-relational impedance mismatch.

13.1.2 Designing TopLink Applications

You can use TopLink to perform a variety of persistence and data transformation functions on any enterprise architecture that uses Java, including:

  • Java EE

  • Spring

  • Java web servers such as Tomcat

  • Java clients such as Java SE and web browsers

13.1.3 Using TopLink in Application Design

TopLink can be used in the following ways:

  • Relational Database Usage: You can use TopLink to persist Java objects to relational databases that support SQL data types accessed using JDBC.

  • Oracle XML Database (XDB) Usage: You can use TopLink to persist XML documents to an Oracle XML database using TopLink direct-to-XMLType mappings.

  • Enterprise Information System (EIS) Usage: You can use TopLink to persist Java objects to an EIS data source using a JCA adapter. In this scenario, the application invokes EIS data source-defined operations by sending EIS interactions to the JCA adapter. Operations can take (and return) EIS records. Using TopLink EIS descriptors and mappings, you can easily map Java objects to the EIS record types supported by your JCA adapter and EIS data source. This usage is common in applications that connect to legacy data sources and is also applicable to web services.

  • XML Usage: You can use TopLink for in-memory, nonpersistent Java object-to-XML transformation with XML Schema (XSD) based XML documents and JAXB. You can use the TopLink JAXB compiler with your XSD to generate both JAXB-specific artifacts (such as content and element interfaces, implementation classes, and object factory class) and TopLink-specific artifacts (such as sessions and project XML files).

13.1.4 Creating TopLink Metadata

The TopLink metadata is the bridge between the development of an application and its deployed runtime environment. You can capture the metadata using:

  • JDeveloper Mapping Editor, which creates TopLink sessions.xml and project.xml files that you pass to the TopLink runtime environment.

  • JPA annotations, persistence.xml, orm.xml, and TopLink JPA annotation and TopLink property extensions. The TopLink JPA persistence provider interprets these metadata sources of metadata to create an in-memory TopLink session and project at runtime.

  • Java and the TopLink API (this approach is the most labor-intensive).

The metadata enables you to pass configuration information into the runtime environment, which uses the information in conjunction with the persistent classes (Java objects, JPA entities, or EJB entity beans) and the code written with the TopLink API, to complete the application.

Using TopLink JPA, you also have the option of specifying your metadata using TopLink sessions.xml and project.xml while accessing your persistent classes using JPA and an EntityManager.

The TopLink metadata architecture provides many important benefits, including the following:

  • By using the metadata, TopLink does not intrude in the object model or the database schema.

  • Allows you to design the object model as needed, without forcing any specific design.

  • Allows DBAs to design the database as needed without forcing any specific design.

  • Does not rely on code-generation (which can cause serious design, implementation, and maintenance issues).

  • Is unobtrusive: adapts to the object model and database schema, rather than requiring you to design their object model or database schema to suit TopLink.

Using TopLink JPA, you have the flexibility of expressing persistence metadata using standard JPA annotations, deployment XML, or both. Optionally, you can take advantage of TopLink JPA annotation and persistence unit extensions.

13.1.5 Creating Project Metadata

A TopLink project contains the mapping metadata that the TopLink runtime uses to map objects to a data source. The project is the primary object used by the TopLink runtime. The principal contents of project metadata include the following:

  • Descriptors

  • Mappings

  • Data Source Login Information

Using JPA, TopLink runtime constructs an in-memory project based on the employed annotations, persistence.xml, orm.xml, and TopLink JPA extensions.

13.1.6 Creating Session Metadata

The TopLink Session configuration file (sessions.xml) allows you to easily manage all of the sessions for a specific project. You can fully customize the information for each session, including your data source login information, JTA transaction usage, and caching.

A TopLink session contains a reference to a particular project.xml file, plus the information required to access the data source. The session is the primary object used by your application to access the features of the TopLink runtime.

The agent responsible for creating and accessing session metadata differs, depending on whether or not you are creating a CMP project. In a POJO project, your application acquires and accesses a session directly. In a CMP project, your application indirectly accesses a session acquired internally by the TopLink runtime.

Using TopLink JPA, the TopLink runtime constructs an in-memory session based on any combination of JPA annotations, persistence.xml, orm.xml, and TopLink JPA annotation and persistence.xml property extensions. The use of a sessions.xml file is optional.

13.1.7 Using TopLink Descriptors

TopLink uses descriptors to store the information that describes how a particular class can be represented by a data source. Descriptors own mappings that associate class instance variables with a data source and transformation routines that are used to store and retrieve values. As such, the descriptor acts as the connection between a Java object and its data source representation.

Two objects – a source (parent or owning) object and a target (child or owned) object are related by aggregation if there is a strict one-to-one relationship between them, and all the attributes of the target object can be retrieved from the same data source representation as the source object. This means that if the source object exists, then the target object must also exist, and if the source object is destroyed, then the target object is also destroyed.

JDeveloper enables you to create the following TopLink descriptor types:

  • Relational Descriptors

  • EIS Descriptors

  • XML Descriptors

13.1.7.1 Relational Descriptors

Relational descriptors describe Java objects that you map to tables in a relational database. Using relational descriptors in a relational project, you can configure relational mappings. In a relational project, you can designate the descriptor as an aggregate, enabling you to configure an aggregate mapping, one that associates data members in the target object with fields in the source object's underlying database tables.

When you designate a relational descriptor as an aggregate, TopLink lets you specify a mapping type for each field in the target class, but defers associating the field with a database table until you configure the aggregate object mapping in the source descriptor. In other words, the target class descriptor defines how each target class field is mapped, but the source class descriptor defines where each target class field is mapped. This lets you share an aggregate object among many parent descriptors mapped to different tables.

13.1.7.2 EIS Descriptors

Describes Java objects that you map to an EIS data source by way of a JCA adapter. EIS descriptors enable you to configure EIS mappings when creating an EIS project.

13.1.7.3 XML Descriptors

Describes Java objects that you map, in memory, to complex types in XML documents defined by an XML schema document (XSD). Using XML descriptors in an XML project, you can configure XML mappings in memory, to XML elements defined by an XSD.

13.1.8 Using TopLink Mappings

TopLink transforms the data from an object representation to a representation specific to a data source. This transformation is called mapping and it is the core of a TopLink project. A mapping corresponds to a single data member of a domain object. It associates the object data member with its data source representation and defines the means of performing the two-way conversion between the object and data source. A TopLink map belongs to a TopLink session, the facade through which applications access TopLink functionality. The available mapping types may vary, depending on the TopLink map and TopLink descriptor.

13.1.8.1 Relational Mapping Types

The relational mappings transform any object data member type to a corresponding relational database representation in any supported relational database. Use them to map simple data types including primitives (such as int), JDK classes (such as String), and large object (LOB) values. You can also use them to transform object data members that reference other domain objects by way of association where data source representations require object identity maintenance (such as sequencing and back references) and possess various types of multiplicity and navigability. The appropriate mapping class is chosen primarily by the cardinality of the relationship

Table 13-1 illustrates the relational mapping types build maps using the TopLink concepts of directionality, transformers, converters, and EJB 2.n CMP relational mapping.

Table 13-1 Relational Mapping Types

Mapping Type Description

Direct-to-field

Map a Java attribute directly to a database field.

Direct-to-XMLType

Map Java attributes to an XMLType column in an Oracle Database.

One-to-one

Map a reference to another persistent Java object to the database.

Variable one-to-one

Map a reference to an interface to the database.

One-to-many

Map Java collections of persistent objects to the database.

Many-to-many

Use an association table to map Java collections of persistent objects to the database.

Direct collection

Map Java collections of objects that do not have descriptors

Direct map

Direct map mappings store instances that implement java.util.Map.

Aggregate object

Create strict one-to-one mappings that require both objects to exist in the same database row.

Transformation

Create custom mappings where one or more fields can be used to create the object to be stored in the attribute.


13.1.8.2 EIS Mapping Types

TopLink enterprise information system (EIS) mappings provide support for accessing legacy data sources and enterprise applications through Java EE Connector architecture (JCA) adapter. TopLink EIS mappings use the JCA Common Client Interface (CCI) to access the EIS through its resource adapter. This provides the ability to directly map from an existing Java object model to any transactional data source, such as mainframes with flat file/hierarchical data. An EIS mapping transforms object data members to the EIS record format defined by the object's descriptor.

Table 13-2 illustrates the EIS mapping types that TopLink provides:

Table 13-2 EIS Mapping Types

Mapping Type Description

Direct mapping

Map a simple object attribute directly to an EIS record.

Composite direct collection mapping

Map a collection of Java attributes directly to an EIS record.

Composite object mapping

Map a Java object to an EIS record in a privately owned one-to-one relationship. Composite object mappings represent a relationship between two classes.

Composite collection mapping

Map a Map or Collection of Java objects to an EIS record in a privately owned one-to-many relationship.

One-to-one mapping

Define a reference mapping that represents the relationship between a single source object and a single mapped persistent Java object.

One-to-many mapping

Define a reference mapping that represents the relationship between a single source object and a collection of mapped persistent Java objects.

Transformation mapping

Create custom mappings where one or more EIS record fields can be used to create the object to be stored in a Java class's attribute.


13.1.8.3 XML Mapping Types

The XML mappings transform object data members to the XML elements of an XML document whose structure is defined by an XML schema document (XSD). You can map the attributes of a Java object to a combination of XML simple and complex types using a wide variety of XML mapping types. TopLink stores XML mappings for each class in the class descriptor. TopLink uses the descriptor to instantiate objects mapped from an XML document and to store new or modified objects as an XML document.

Table 13-3 indicates the XML mapping types you can use to map the attributes of a Java object to a combination of XML simple and complex types:

Table 13-3 XML Mapping Types

Mapping Type Description

XML Direct Mapping

Map a simple object attribute to an XML attribute or text node.

XML Composite Direct Collection Mapping

Map a collection of simple object attributes to XML attributes or text nodes.

XML Composite Object Mapping

Map any attribute that contains a single object to an XML element. The TopLink runtime uses the descriptor for the referenced object to populate the contents of that element.

XML Composite Collection Mapping

Map an attribute that contains a homogenous collection of objects to multiple XML elements. The TopLink runtime uses the descriptor for the referenced object to populate the contents of those elements.

XML Any Object Mapping

The XML Any Object mapping is similar to the XML Composite Object mapping except that the reference object may be of different types (including String), not necessarily related to each other through inheritance or a common interface.

XML Any Collection Mapping

The XML Any Collection mapping is similar to the XML Composite Collection mapping except that the referenced objects may be of different types (including String), not necessarily related to each other through inheritance or a common interface.

XML Transformation Mapping

Create custom mappings where one or more XML nodes can be used to create the object to be stored in a Java class's attribute.


13.1.9 Understanding the TopLink Editor

Use the TopLink editor to configure and map Java classes to different data sources, including relational databases, enterprise information systems (EIS), and XML schemas without using code. The TopLink editor supports multiple mapping standards, including EJB 3.0 JPA.

The TopLink editor displays the information or properties specific to the element selected in the Application Navigator or the Structure view. For example, selecting TopLink project elements in the Application Navigator, such as a the TopLink Map or the sessions configuration file (sessions.xml), enables you to configure their properties in the TopLink editor. Likewise, selecting TopLink Maps, descriptors, and mapped or unmapped attributes in the Structure view results in the display of their respective properties in the TopLink editor.

13.1.9.1 Managing TopLink Maps

The TopLink Map contains the information about how classes map to database tables or XML schema. Use the TopLink editor to edit each component of the mappings, including:

  • Database information, such as driver, URL, and login information.

  • Mapping defaults, such as identity map and cache options.

To configure a TopLink Map, choose Application Navigator context menu for a TopLink Map (for example, tlMap) Open or choose the Structure view for TopLink Map. The TopLink editor displays the properties for the object map depending on its type, such as relational, or EIS. When using the TopLink editor for relational object maps, for example, you can configure the sequencing policy. For more information about TopLink editor, see Oracle Fusion Middleware Developer's Guide for Oracle TopLink.

TopLink mappings use descriptors to store the information that describes how an instance of a particular class can be represented in the data source. To configure a map's descriptors, choose Structure view for tlMap descriptor. For example, using the editor, you can improve application performance by creating named queries and also prevent users from overwriting each other's work by configuring locking policies.

TopLink mappings define how an object's attributes are represented in the data source. The Structure view enables you to configure the mappings for the descriptor's attributes by choosing Structure view for tlMap descriptor attribute Map as context menu mapping type.

13.1.9.2 Managing TopLink Sessions

The TopLink Sessions configuration file (sessions.xml) enables you to manage all of the sessions for a specific project. For more information about TopLink sessions, see Oracle Fusion Middleware Developer's Guide for Oracle TopLink.

By choosing Structure view for sessions.xml Open, you can use the TopLink editor to fully customize the information for each session, such as data source login information, JTA transaction usage, and caching. You can also use the TopLink editor to create and configure individual sessions and the session brokers that manage them. To manage session brokers, Structure view for sessions.xml session broker.

13.1.9.3 Managing Persistence Configurations

The TopLink editor enables you to configure the persistence.xml file, which packages entities in TopLink JPA projects. By choosing Application Navigator for persistence.xml Open, you can create persistence units.

The Structure window displays JPA descriptors and persistence units. By choosing Structure view for persistence.xml persistence unit, you can configure the persistence unit.

13.1.9.4 The TopLink Structure View Toolbar

The Structure view displays detailed information about the TopLink element selected in Application Navigator or TopLink editor. For example:

  • When working with an EJB or Java class, the Structure view displays the related TopLink descriptor and its mapping attributes.

  • When working with a TopLink sessions configuration file, the Structure view displays sessions and session brokers.

  • When working with a persistence configuration, the Structure view displays JPA descriptors and persistence units.

The Structure view contains a toolbar that provides access to modify descriptors, mapping, sessions, and persistence units. This toolbar is context-sensitive; the buttons displayed vary depending on the element that you select in the Structure view.

Table 13-4 Icons in the TopLink Structure View Toolbar

Icon Name Function
Add or Remove Descriptors

Add or Remove Descriptors

Adds or removes descriptors from the TopLink map

Automap

Automap

Attempts to automap the selected descriptor or attribute to a similarly named database field.

Aggregate Descriptor

Aggregate Descriptor

Changes the descriptor type to aggregate descriptor, meaning that the descriptor's definitions for table, primary key and other options are from the owning descriptor.

Class Descriptor

Class Descriptor

Changes the descriptor type to class descriptor.

Map As

Map As

Selects a mapping type for the selected attribute.

New Persistence Unit

New Persistence Unit

Click to create a new persistence unit.

Create a New Database or Server Session

Create a New Database or Server Session

Click to create a session within the sessions configuration file.

Create Session Broker

Create Session Broker

Click to create a new session broker.

Create a New Named Connection Pool

Create a New Named Connection Pool

Click to create a new named connection pool, a connection pool used for any purpose, but typically for security purposes.

Add the Sequence Connection Pool

Add the Sequence Connection Pool

Click to add a connection pool exclusively used for sequencing. TopLink uses the sequence connection pool whenever it needs to assign an identifier to a new object.


13.1.9.5 TopLink Project Elements in the Application Navigator

The Application Navigator displays each element associated with your TopLink project, including the TopLink Map, deployment descriptors, and sessions configuration information.

TopLink project elements in the Application Navigator may include:

  • TopLink folder

  • Sessions configuration file (sessions.xml)

  • TopLink map (tlMap)

13.1.9.6 TopLink Editor Tabs in the Editor Window

The TopLink Editor displays your TopLink mapping information. The information in the editor will vary, depending on the TopLink element you selected in the Application Navigator or Structure view.

13.1.9.7 TopLink Project Elements in the Structure View

The Structure view displays detailed information about the TopLink element selected in Application Navigator or TopLink Editor:

  • When working with an EJB or Java class, the Structure view displays the related TopLink descriptor and its mapping attributes.

  • When working with a TopLink sessions configuration file, the Structure view displays your sessions and session brokers.

  • When working with a persistence configuration, the Structure view displays your JPA descriptors and persistence units.

When you select an item in the Structure view, the following properties appear in the TopLink Editor:

  • TopLink map (tlMap)

  • Descriptor

  • Mapped Java attribute (one-to-one mapping)

  • Unmapped attribute

You can perform specific functions for an item by selecting the item in the Application Navigator and then:

  • Right-clicking the object in Structure view and selecting the function from the pop-up menu.

  • Selecting the object in Structure view and clicking a button in the Structure toolbar.

13.1.9.8 Using the TopLink Structure View Toolbar

The TopLink Editor Structure view contains a toolbar that offers quick access to modify descriptors and mappings. This toolbar is context-sensitive; the actual buttons displayed will vary, depending on which element in the Structure view is selected.

13.1.9.9 TopLink Mapping Status Report in Message Log

Error and status messages from the TopLink Editor appear in the TopLink Problems window.

13.1.9.10 Configuring TopLink Preferences

You can configure which persistence provider to use, which JPQL editor to use, and query types and formats.

To configure TopLink Editor preferences:

  1. Select Tools > Preferences.

  2. In the Categories list, expand TopLink Customization.

  3. Configure JPA and Mappings options.

  4. Complete each field and click OK.

13.1.9.11 How to Create a TopLink Mapping Project

JDeveloper stores the TopLink descriptors (for more information, see Section 13.1.7, "Using TopLink Descriptors") and mappings (for more information, see Section 13.1.8, "Using TopLink Mappings") in a TopLink map (.mwp file), and sessions in the sessions.xml file. The TopLink map contains the information about how classes map to database tables. Use the TopLink Editor to edit each component of the mappings, including:

  • Database information, such as driver, URL, and login information.

  • Mapping defaults, such as cache options.

When you select a TopLink map (or an element in a TopLink map), its attributes display in the TopLink Editor.

TopLink maps persistent entities to the database in the application using the descriptors and mappings you build with JDeveloper Mapping Editor. The Mapping Editor supports such approaches to project development as:

  • Importing classes and tables for mapping.

  • Importing classes and generating tables and mappings.

  • Importing tables and generating classes and mappings.

  • Creating both class and table definitions.

Although JDeveloper Mapping Editor offers the ability to generate persistent entities or the relational model components for an application, these utilities are intended only to assist in rapid initial development strategies–not complete round-trip application development.

To create a new TopLink-enabled project:

  1. Select File > New.

  2. In the Categories list, choose General > Projects.

  3. In the Items list, select TopLink Project.

  4. Click OK.

    The New TopLink-Enabled Project dialog displays.

  5. Complete each field and click OK.

    JDeveloper creates a new project, including an object map.

To add a TopLink map to an existing JDeveloper project:

  1. Right-click an existing project in the Application Navigator and choose New.

  2. In the Categories list, choose Business Tier > TopLink/JPA.

  3. In the Items list, select TopLink Object Map.

  4. Complete each field and click OK.

    JDeveloper creates a TopLink map file in an existing project.

13.1.9.12 How to Use Converter Mappings

TopLink no longer uses the following direct mapping types:

  • Type conversion

  • Object type

  • Serialized object

Instead, TopLink uses a direct-to-field mapping with a specialized converter. To generate backward-compatible deployment XML files, use the Generate Deprecated Direct Mappings option on the General page of the TopLink Map options.

13.1.9.13 How to Automap TopLink Descriptors

The TopLink Automap wizard can automatically map your Java class attributes to a similarly named database field. The Automap wizard only creates mappings for unmapped attributes; it does not change previously defined mappings.

You can use the Automap wizard for an entire project or for specific classes or descriptors.

To automap TopLink descriptors:

  1. In the Application Navigator, select a TopLink Map.

    The TopLink Map (and its attributes) appear in the Structure window.

  2. In the Structure window, right-click the TopLink Map (or a specific Java class or TopLink descriptor) and choose Automap.

    The Automap Wizard wizard displays. Complete each page of the wizard.

13.1.9.14 Data Source Login Information

For TopLink mappings, you can configure a session login in the session metadata that specifies the information required to access the data source.

13.2 Developing TopLink JPA Projects

Use a TopLink JPA (Java Persistence API) project for persisting Java objects based on Plain Old Java Objects (POJOs).

The Java Persistence API is a lightweight framework for Java persistence based on Plain Old Java Objects. JPA is a part of EJB 3.0 specification. JPA provides an object-relational mapping approach that enables you to declaratively define how to map Java objects to relational database tables in a standard, portable way. In addition, this API enables you to create, remove and query across lightweight Java objects within both an EJB 3.0-compliant container and a standard Java SE 5 and Java SE 6 environment.

The TopLink implementation of JPA is provided by EclipseLink. For more information, see http://wiki.eclipse.org/EclipseLink.

You can perform object relational mapping with TopLink JPA through the following:

Table 13-5 Methods for Performing Object Relational Mapping with TopLink JPA

Method Description

Using Metadata Annotations

An annotation is a simple, expressive means of decorating Java source code with metadata that is compiled into the corresponding Java class files for interpretation at run time by a JPA persistence provider to manage persistent behavior.You can use annotations to configure the persistent behavior of your entities.

Using XML

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.

Defaulting Properties

Each annotation has a default value. A persistence engine defines defaults that apply to the majority of applications. To override the default value, you need only to supply the appropriate values. A configuration value is not a requirement, but the exception to the rule. This is known as configuration by exception.

Configuring an Entity

You can configure an entity's identity, as well as the locking technique and sequence generation option for the entity.

Declaring Basic Property Mappings

Simple Java types are mapped as part of the immediate state of an entity in its fields or properties. Mappings of simple Java types are called basic mappings. By default, TopLink persistence provider automatically configures a basic mapping for simple types.

Mapping Relationships

TopLink persistence provider requires that you map relationships explicitly. Use such annotations as @OnetoOne, @ManytoOne, @OnetoMany, @ManytoMany, @Mapkey, and @Orderby to specify the type and characteristics of entity relationships that fine-tune how the database implements relationships.

Mapping Inheritance

By default, TopLink persistence provider assumes that all persistent fields are defined by a single entity class. Use the @Inheritance, @MappedSuperclass, @DiscriminatorColumn, and @DiscriminatorValue annotations if your entity class inherits some or all persistent fields from one or more superclasses.

Mapping Embedded Objects

An embedded object does not have its own persistent identity. It is dependent upon an entity for its identity. By default, TopLink persistence provider assumes that every entity is mapped to its own table. Use the following annotations to override this behavior for entities that are owned by other entities:

  • @Embeddable

  • @Embedded

  • @AttributeOverride

  • @AttributeOverrides

  • @AssociationOverride

  • @AssociationOverrides


13.2.1 How to Create and Configure a JPA Persistence Descriptor (persistence.xml)

Use the persistence configuration file (persistence.xml) file to package your entities.

To create a persistence configuration:

  1. Select File > New.

  2. In the Categories list, select Business Tier > TopLink/JPA.

  3. In the Items list, select JPA Persistence Descriptor.

  4. Click OK.

    The New JPA Persistence Descriptor dialog displays.

  5. Complete the fields to create a default persistence unit for the new JPA persistence descriptor file (persistence.xml) and click OK.

    Example 13-1 contains a sample persistence configuration.

Example 13-1 Sample Persistence Configuration (persistence.xml)

<?xml version="1.0" encoding="windows-1252" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
 <persistence-unit name="myPersistenceUnit">
   <properties>
      <property name="toplink.target-database" value="Oracle11g"/>
       <property name="toplink.target-server" value="WebLogic_10"/>
   </properties>
 </persistence-unit>
 <persistence-unit name="myPersitenceUnitName">
...
 </persistence-unit>
</persistence>

To configure a persistence configuration (persistence.xml) file:

  1. Select the persistence.xml node in the Application Navigator.

  2. In the Structure window, select the JPA Persistence Descriptor.

  3. Complete the General and Metadata Preferences tabs on the JPA Persistence descriptor (persistence.xml) page.

13.2.2 How to Create Persistence Units

To create a persistence unit:

  1. Double-click the persistence configuration file (persistence.xml) in the Application Navigator or Structure window.

  2. On the General page, click Create New Persistence Unit to create a new persistence unit.

  3. Complete each field on the New Persistence Unit dialog.

  4. On the Metadata Preferences page, specify how to persist new mapping metadata. You can specify annotations or JPA mapping descriptors. In order to make this choice, you must first create at least one orm.xml mapping descriptor file. (See Section 13.2.4, "How to Create JPA Descriptors.")

    Example 13-2 contains a sample persistence unit.

Example 13-2 Example Persistence Unit

...
 <persistence-unit name="myPersitenceUnitName"
           transaction-type="RESOURCE_LOCAL">
     <mapping-file>META-INF/orm.xml</mapping-file>
     <exclude-unlisted-classes/>
     <properties>
       <property name="eclipselink.jdbc.driver" 
                 value="oracle.jdbc.OracleDriver"/>
       <property name="eclipselink.jdbc.url"
                 value="jdbc:oracle:thin:@localhost:1521:XE"/>
       <property name="eclipselink.jdbc.user" value="scott"/>
       <property name="eclipselink.jdbc.password"
                 value="3E20F8982C53F4ABA825E30206EC8ADE"/> 
       <property name="eclipselink.target-database" value="Oracle11g"/>
       <property name="eclipselink.logging.level" value="FINER"/>
       <property name="eclipselink.jdbc.native-sql" value="true"/> 
       <property name="eclipselink.target-server" value="WebLogic_10"/>
     </properties>
 </persistence-unit>
...

13.2.3 How to Configure Persistence Units

The tabs of the Persistence Unit page (accessed by first selecting persistence.xml in the Application Navigator and then expanding the JPA descriptor in the Structure view) enable you to configure a persistence unit.

Configuring Persistence Units encompasses many steps, such as configuring:

  • General information

  • Connection information

  • TopLink information

  • Schema generation information

  • Properties

  • Metadata information

To configure the general information for a JPA persistence unit:

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the General tab to specify how the persistence unit connects to the application server and database.

To configure the connection information for a JPA persistence unit:

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the Connection tab to select a persistence provider and configure its general properties (such as JPA mapping descriptors, Java archives, and mapped classes).

To configure the TopLink session-specific information for a JPA persistence unit:

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the TopLink Customization tab to specify TopLink-specific information for the persistence unit.

To configure the DDL generation options:

Although most JPA persistence providers provide this support, these options are TopLink-specific.

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the Schema Generation tab to specify how the TopLink generates the DDL scripts.

To configure the non-TopLink specific properties for the persistence unit:

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the Properties tab to specify the general, non-TopLink specific properties.

To configure metadata overrides for a persistence unit:

  1. Select the JPA persistence descriptor (persistence.xml) in the Application Navigator.

  2. Select the persistence unit in the Structure window.

    The Persistence Unit page displays.

  3. Complete the fields on the Metadata Preferences tab to specify the information for the mapping descriptor.

    This tab is available only if the persistence unit contains a JPA mapping descriptor.

13.2.4 How to Create JPA Descriptors

The JPA mapping descriptor is used as an alternative to annotations. Any information you add as a JPA mapping descriptor will override the Java annotations.

To create new JPA mapping descriptors:

  1. Select the persistence configuration (persistence.xml) in the Application Navigator.

  2. Select the General tab.

  3. In the JPA Mapping Descriptors area, click the Create New JPA Mapping Descriptor button.

  4. Complete the fields on the dialog and click OK.

    JDeveloper adds the Mapping Descriptors (orm.xml) to the project.

  5. Complete the following tabs for each JPA descriptor on the ORM (orm.xml) page:

    • General

    • Persistence Unit Defaults

    • Generators

    • Queries

To configure the general information for a JPA mapping descriptor:

  1. Select the JPA mapping descriptor (orm.xml) in the Application Navigator.

  2. Select the descriptor in the Structure window.

    The ORM (orm.xml) page appears.

  3. Complete the fields on the General tab to select a persistence provider and configure its general properties (such as mapped classes, development database, and other defaults).

13.2.4.1 How to Configure Persistence Unit Defaults

You can configure the settings that apply to persistence units and associated entities that include this mapping descriptor. These values will be overridden by any configuration settings at the persistence unit-level.

To configure persistence unit defaults:

  1. Select the JPA mapping descriptor (orm.xml) in the Application Navigator.

  2. Select the descriptor in the Structure window.

    The ORM (orm.xml) page appears.

  3. Complete the fields on the Persistence Unit Defaults tab to configure the access type, entity listeners, and other defaults.

13.2.4.2 How to Configure Generators

You can define the generators used by this mapping descriptor.

To configure generators:

  1. Select the JPA mapping descriptor (orm.xml) in the Application Navigator.

  2. Select the descriptor in the Structure window.

    The ORM (orm.xml) page appears.

  3. Complete the fields on the Generators tab to configure the database sequence and table generators.

13.2.4.3 How to Configure Queries

You can define the JPQL and native queries in this mapping descriptor for use in associated persistence units.

To configure queries:

  1. Select the JPA mapping descriptor (orm.xml) in the Application Navigator.

  2. Select the descriptor in the Structure window.

    The ORM (orm.xml) page appears.

13.2.5 Using JPA Mappings

Oracle TopLink provides a complete, JPA 2.0-compliant JPA implementation. It provides complete compliance for all of the mandatory features, many of the optional features, and some additional features.

TopLink offers support for deployment within an EJB 3.0 container or outside the container. This includes Web containers, other non-EJB 3.0 Java EE containers, and the Java SE environment.

Through its pluggable persistence capabilities TopLink can function as the persistence provider in any compliant EJB 3.0 container.

13.2.6 Using TopLink Extensions

The Java Persistence API (JPA), part of the Java Enterprise Edition 5 (Java EE 5) EJB 3.0 specification, greatly simplifies Java persistence. It 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's own XML metadata, and custom API.

13.3 Developing TopLink Relational Projects

The TopLink Editor provides complete support for creating relational projects that map Java objects to a conventional relational database accessed using JDBC. Use a TopLink relational project for transactional persistence of Java objects to a conventional relational database or to an object-relational database that supports data types specialized for object storage, both accessed using JDBC.

To create relational projects for an object-relational database, you must create the project using Java code. You can create a relational project for transactional persistence of Java objects to an object-relational database that supports data types specialized for object storage (such as Oracle Database) accessed using JDBC.

13.3.1 How to Create Relational Projects and Object Maps

To create relational projects for an object-relational database, you must create the project using Java code. You can create a relational project for transactional persistence of Java objects to an object-relational database that supports data types specialized for object storage (such as Oracle Database) accessed using JDBC.

To create a new relational project:

  1. Select File > New.

  2. In the Categories list select General > Projects.

  3. In the Items list, select TopLink Project.

  4. Click OK.

    The New TopLink-Enabled Project dialog displays.

  5. Complete the fields on the dialog to specify the project name, project location, and TopLink map.

  6. In the Data Source area, select Database, then specify your specific database information.

  7. Click OK.

    JDeveloper creates a new project, including the TopLink map and TopLink sessions configuration file (sessions.xml).

To create a new TopLink object map for a relational project:

  1. Select File > New.

  2. In the Categories list select Business Tier > TopLink/JPA.

  3. In the Items list, select TopLink Object Map.

  4. Click OK.

    The New TopLink Object Map dialog displays.

  5. Complete the fields on the dialog to specify the TopLink map.

  6. In the Data Source area, select Database, then specify your specific database information.

  7. Click OK.

    JDeveloper creates a new project, including the TopLink map and TopLink sessions configuration file (sessions.xml).

13.3.2 How to Create Relational Descriptors

Relational descriptors describe Java objects that you map to tables in a relational database. In a relational project, you can designate the descriptor as a class descriptor or an aggregate descriptor.

A class descriptor is applicable to any persistent object, but not an aggregate object. Using a class descriptor, you can configure any relational mapping except aggregate collection and aggregate object mappings.

An aggregate object is an object that is strictly dependent on its owning object. Aggregate descriptors do not define a table, primary key, or many of the standard descriptor options as they inherit these from their owning descriptor. If you want to configure an aggregate mapping to associate data members in a target object with fields in a source object's underlying database tables, you must designate the target object's descriptor as an aggregate.

You can configure inheritance for a descriptor designated as an aggregate, however, in this case, all the descriptors in the inheritance tree must be aggregates. Aggregate and class descriptors cannot exist in the same inheritance tree.

You can change a class descriptor to an aggregate descriptor, or remove the aggregate designation from a relational descriptor and return it to its default type. For more information, see Section 13.3.3, "How to Configure Relational Descriptors.".

Note:

When you change a class descriptor to an aggregate descriptor, the descriptor's existing information is permanently lost. If you convert the descriptor back to a class descriptor, you will have to configure it again.

To create new TopLink descriptors:

  1. Right-click the TopLink Map in the Application Navigator and select Add or Remove Descriptors.

  2. Select the packages and classes from which to create TopLink descriptors and click OK.

    JDeveloper adds the descriptors to the TopLink Map in the Structure window.

13.3.3 How to Configure Relational Descriptors

You can configure a relational descriptor as a Class type or an Aggregate type. By default, when you add a Java class to a relational project, JDeveloper automatically creates a relational class descriptor for it.

You can change a class descriptor to an aggregate descriptor.

To configure a TopLink relational class descriptor to an aggregate descriptor:

  1. Select the TopLink Map in the Application Navigator.

  2. In the Structure window, right-click the descriptor and from the Descriptor Type submenu, select Aggregate.

    The selected descriptor is now an aggregate descriptor.

  3. To convert an aggregate descriptor to a class descriptor, right-click the descriptor and from the Descriptor Type submenu, select Class.

13.4 Developing TopLink XML Projects

Use an XML project for nontransactional conversions between Java objects and XML documents using JAXB (Java Architecture for XML Binding) which defines annotations to control the mapping of Java objects to XML.

The TopLink runtime performs XML data conversion based on one or more XML schemas. In an XML project, the TopLink Editor directly references schemas in the deployment XML and exports mappings configured with respect to the schemas you specify.

TopLink provides an extra layer of functions on top of JAXB. In particular, TopLink provides the TopLink JAXB compiler, which generates both JAXB- and TopLink-specific files.

The JAXB complier generates implementation classes that are named according to the content, element, or implementation of the name attribute in the XSD. The generated implementation classes are simple domain classes with private attributes for each JAXB property. Public get and set methods return or set attribute values.

The JAXB complier generates TopLink project files, session.xml files, and TopLink project XML files. The TopLink JAXB compiler generates a single class called DescriptorAfterLoads if any implementation class contains a mapping to a type safe enumeration.

TopLink can validate both complete object trees and subtrees against the XML schema that was used to generate the implementation classes. In addition, TopLink will validate both root objects (objects that correspond to the root element of the XML document) and non-root objects against the schema used to generate the object's implementation class.

JAXB provides a standard Java object-to-XML API. JAXB defines annotations to control the mapping of Java objects to XML. For more information, see http://www.oracle.com/technetwork/java/index-jsp-137051.html.

JAXB also defines a default set of mappings which TopLink uses to marshal a set of objects into XML, and unmarshall an XML document into objects. TopLink provides an extra layer of functions on top of JAXB. It allows for the creation and subsequent manipulation of TopLink mappings from an existing object model, without requiring the recompilation of the JAXB object model.

13.4.1 How to Create XML Projects

To create a new XML project:

  1. Select File > New.

  2. In the Categories list select General > PropertiesTopLink.

  3. In the Items list, select TopLink Project.

  4. Click OK.

    The New TopLink-Enabled Map dialog appears.

  5. Complete the fields on the dialog to specify the project name, project location, and TopLink map.

  6. In the Data Source area, select Database, then specify your specific database information.

  7. Click OK.

    JDeveloper adds the TopLink map and TopLink sessions configuration file (sessions.xml).

13.4.2 How to Create XML Object Maps

To create a new TopLink object map:

  1. Select File > New.

  2. In the Categories list select Business Tier > TopLink/JPA.

  3. In the Items list, select TopLink Object Map.

  4. Click OK.

    The New TopLink-Enabled Map dialog appears.

  5. Complete the fields on the dialog to specify the project name, project location, and TopLink map.

  6. In the Data Source area, select XML.

  7. Click OK.

    JDeveloper adds the TopLink map and TopLink sessions configuration file (sessions.xml).

13.4.3 How to Create XML Descriptors

To create new TopLink descriptors for an XML project:

  1. Right-click the TopLink Map in the Application Navigator and select Add or Remove Descriptors.

  2. Select the packages and classes from which to create TopLink descriptors and click OK.

    JDeveloper adds the descriptors to the TopLink element in the Structure window.

  3. Complete the fields on the XML Descriptor page to configure the descriptor.

13.4.4 How to Add XML Schemas

If you have an existing data model (XML schema document), but you do not have a corresponding object model (Java classes for domain objects), use this procedure to create your TopLink project and automatically generate the corresponding object model.

To add an XML schema:

  1. Select the TopLink map in the Application Navigator.

  2. In Structure window, right-click the Schemas element and select Import Schema.

  3. Complete the fields on the dialog to specify the XML schema to import.

  4. Click OK.

    JDeveloper adds the schema (tlmap) to the TopLink map

Using the TopLink JAXB compiler simplifies JAXB application development with TopLink by automatically generating both the required JAXB files and the TopLink files from your XML schema (XSD) document. Once generated, you can fine-tune XML mappings without having to recompile your JAXB object model.

13.5 Developing TopLink EIS Projects

Use a TopLink EIS project for transactional persistence of Java objects to a nonrelational data source accessed using a Java EE Connector Architecture (JCA) adapter and EIS records.

Oracle recommends using EIS projects to integrate TopLink with a legacy or nonrelational data source. TopLink provides support for mapping Java objects to EIS mapped, indexed, and XML records, through J2C, using the TopLink mappings. J2C provides a Common Client Interface (CCI) API to access nonrelational EIS. This provides a similar interface to nonrelational data sources as JDBC provides for relational data sources.

EIS includes legacy data sources, enterprise applications, legacy applications, and other information systems. These systems include such sources as Customer Information Control System (CICS), Virtual Storage Access Method (VSAM), Information Management System (IMS), ADABASE database, and flat files. Oracle recommends using EIS projects to integrate TopLink with a legacy or nonrelational data source. Other methods of accessing EIS data sources include:

13.5.1 How to Create EIS Projects

Use an EIS project for transactional persistence of Java objects to a nonrelational data source accessed using a Java EE Connector Architecture (JCA) adapter and EIS records.

To create an EIS project:

  1. Select File > New.

  2. In the Categories list select General > Projects.

  3. In the Items list select TopLink Project.

  4. Click OK.

  5. Complete the fields on the dialog to specify the project name, project location, and TopLink map.

  6. In the Data Source area, select EIS, then specify your specific EIS platform.

  7. Click OK.

    JDeveloper creates a new project, including the TopLink map and TopLink sessions configuration file (sessions.xml).

13.5.2 How to Create EIS Object Maps

An EIS mapping transforms object data members to the EIS record format defined by the object's descriptor.

To create a new TopLink object map for an EIS project:

  1. Select File > New.

  2. In the Categories list select Business Tier > TopLink/JPA.

  3. In the Items list select TopLink Object Map.

  4. Click OK.

  5. Complete the fields on the dialog to specify the TopLink map.

  6. In the Data Source area, select EIS, then specify your specific EIS platform.

  7. Click OK.

    JDeveloper adds the TopLink map to the project.

13.5.3 How to Create EIS Descriptors

EIS descriptors describe Java objects that you map to an EIS data source by way of a JCA adapter.

To create an EIS descriptor:

  1. Select the TopLink map in the Structure window.

  2. Click the Add or Remove Descriptors from the Selected TopLink Map button.

  3. Select the classes from which to create an EIS descriptor and click OK.

    JDeveloper adds the EIS descriptors to the Structure window.

  4. Complete the property tabs for the EIS Descriptor.

13.5.4 Using EIS Data Sources

For each EIS project, you must specify one of the following JCA data source platforms that you will be using:

  • Oracle AQ

  • Attunity Connect

  • IBM MQSeries

This platform configuration is overridden by the session login, if configured.

13.6 Developing TopLink Sessions

Each TopLink map belongs to aTopLink session. A session is the facade through which an application accesses TopLink functionality. A session associates data source platform information, data source login information, and mapping metadata for a particular application. You can reuse mapping metadata in different applications by defining different sessions.

TopLink session provides the primary access to the TopLink runtime. It enables applications to perform persistence operations with the data source that contains persistent objects. A session associates data source platform information, data source login information, and mapping metadata for a particular application. You can reuse mapping metadata in different applications by defining different sessions.

TopLink provides different session types, each optimized for different design requirements and data access strategies. You can combine different session types in the same application.

The TopLink Editor provides the following TopLink sessions:

Other session types are can be configured directly in Java code. For more information about session types, see the Oracle Fusion Middleware Developer's Guide for Oracle TopLink.

13.6.1 How to Create a New Sessions Configuration File

Each TopLink sessions configuration (sessions.xml file) can contain multiple sessions and session brokers. In addition, you can specify a classpath for each sessions configuration that applies to all the sessions it contains.

To create a new sessions configuration file:

  1. Select File > New.

  2. In the Categories list, select Business Tier > TopLink/JPA.

  3. In the Items list, select TopLink Sessions Configuration.

  4. Click OK.

    The Create TopLink Sessions Configuration dialog appears.

  5. Complete each field on the dialog and click OK.

    In Application Navigator, JDeveloper adds the sessions.xml file in the folder where it was created and the default session to the sessions configuration node in the Structure view.

13.6.2 How to Create Sessions

A TopLink session provides the primary access to the TopLink runtime. It is the means by which your application performs all persistence operations with the data source that contains persistent objects.

A session associates data source platform information, data source login information, and mapping metadata for a particular application. You can reuse mapping metadata in different applications by defining different sessions.

To create a new TopLink session:

  1. In the Application Navigator, right-click a TopLink sessions configuration file and select Open.

    The TopLink sessions configuration file appears in the TopLink Editor, showing the existing sessions and session brokers in this sessions configuration file.

  2. Click Create a New Session.

  3. Complete each field in the New Session dialog and click OK.

    JDeveloper adds the new session to the sessions configuration node in the Structure view.

13.6.3 Acquiring Sessions at Runtime

After you create and configure sessions, you can use the TopLink session manager to acquire a session instance at run time. The TopLink session manager enables developers to build a series of sessions that are maintained under a single entity. The session manager is a static utility class that loads TopLink sessions from the sessions.xml file, caches the sessions by name in memory, and provides a single access point for TopLink sessions.

The session manager has two main functions: it creates instances of the sessions and it ensures that only a single instance of each named session exists for any instance of a session manager.

The session manager instantiates sessions as follows:

  • The client application requests a session by name.

  • The session manager looks up the session name in the sessions.xml file. If the session name exists, the session manager instantiates the specified session; otherwise, it raises an exception.

  • After instantiation, the session remains viable until you shut down the application.

Once you have a session instance, you can use it to acquire additional types of sessions for special tasks. This is particularly useful for EJB applications in that an enterprise bean can acquire the session manager and acquire the desired session from it.

13.6.4 How to Create Session Brokers

The session broker is a mechanism that enables client applications to transparently access multiple databases through a single TopLink session. A session broker may contain both server sessions and database sessions. Oracle recommends that you use the session broker with server sessions because server sessions are the most scalable session type.

After you create and configure a session broker with server sessions, you can acquire a client session from the session broker at run time to provide a dedicated connection to all the data sources managed by the session broker for each client.

To create a new session broker:

  1. In the Application Navigator, open the sessions configuration file (sessions.xml).

    The sessions configuration displays in the TopLink Editor.

  2. Click Create a New Session Broker.

  3. Complete each field in the dialog, select the sessions to add to the session broker, and then click OK.

13.6.5 How to Create Data Source Logins

The TopLink sessions configuration file (sessions.xml) overrides any login information that you specified in the TopLink map. You can create data source logins for relational database or EIS data sources.

To create a data source:

  1. Select the TopLink sessions configuration (sessions.xml) in the Application navigator.

  2. Expand the sessions node in the sessions.xml Structure view and then select the TopLink session.

    The TopLink session information appears in the TopLink Editor.

  3. Select the Login tab.

  4. Complete the Connection information.

13.6.6 How to Create Connection Pools

A connection pool is a service that creates and maintains a shared collection (pool) of data source connections on behalf of one or more clients. The connection pool provides a connection to a process on request, and returns the connection to the pool when the process is finished using it. When it is returned to the pool, the connection is available for other processes.

Because establishing a connection to a data source can be time-consuming, reusing such connections in a connection pool can improve performance. TopLink uses connection pools to manage and share the connections used by server and client sessions. Reusing connections to a single data source reduces the number of connections required and allows your application to support many clients.

To create a new connection pool.

  1. Select the TopLink sessions configuration (sessions.xml) in the Application navigator.

  2. Expand the sessions node in the sessions.xml Structure window and then select the TopLink session.

  3. Right-click the session and select New > Named Connection Pool from the context menu.

  4. Enter a name for the connection pool and click OK.

    JDeveloper adds the connection pool to the Structure window.

  5. Select the newly created connection pool.

    Its properties appear in the Connection Pool page in the Editor window.

13.7 Developing TopLink Applications

Oracle TopLink is an advanced, object-persistence and object-transformation framework that provides development tools and run-time capabilities that reduce development and maintenance efforts, and increase enterprise application functionality.

13.7.1 Using TopLink the Cache

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:

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

TopLink uses two types of cache:

  • Session Cache – A shared cache that services clients attached to a given session. When a client session reads objects from, or writes them to, a data source, 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.

    TopLink adds objects to the session cache from the following:

    • The data store, when TopLink executes a read operation.

    • The unit of work cache, when a unit of work successfully commits a transaction.

  • Unit of Work Cache – Services operations within the unit of work. It maintains and isolates objects from the session cache, and writes changed or new objects to the session cache after the unit of work commits changes to the data source. TopLink updates the sessions cache when a unit of work commits to the data source.

13.7.1.1 Object Identity

TopLink preserves object identity through its cache using the primary key attributes of a persistent entity, which may or may not be assigned through sequencing. Oracle recommends that you always maintain object identity. Disable object identity only if absolutely necessary, for example, for read-only objects.

13.7.1.2 Querying and the Cache

A query that is run against the shared session cache is known as an in-memory query.

By default, a query that looks for a single object based on primary key attempts to retrieve the required object from the cache first, searches the data source only if the object is not in the cache. All other query types search the database first, by default. You can specify whether a given query runs against the in-memory cache, the database, or both.

13.7.1.3 Handling Stale Data

Stale data is an artifact of caching, in which an object in the cache is not the most recent version committed to the data source.

13.7.1.4 Explicit Query Refreshes

For systems that require several objects be current, you can specify that these objects be explicitly refreshed from the database without incurring the full cost of distributed cache coordination. To do this:

  1. Configure a set of queries that refresh the required objects.

  2. Establish an appropriate refresh policy.

  3. Invoke the queries as required to refresh the objects.

13.7.1.5 Cache Invalidation

Use a cache invalidation policy to specify how or when a cached object becomes invalid. Using cache invalidation ensures that an application does not use stale data. You can configure the cache to invalidate objects at a certain time of day, mark an object as invalid after a specified time period after the object was read, or you can set the set the invalidation policy to invalidate an object only explicitly. You can set an invalidation policy to apply to all objects by configuring it at the project level, to certain objects by applying it at the descriptor level, or to the results returned by a query by applying it at the query level.

13.7.1.6 Cache Coordination

Cache coordination enhances performance by avoiding data source access. By enabling the instances of a session to broadcast object changes to one another so that each session's cache is kept current or notified that the cache must update an object from the data source the next time that it is read, it also reduces stale data. In addition, cache coordination reduces the optimistic lock exceptions in distributed environments as well as the number of failed or repeated transactions in an application. Use cache coordination for applications that are read-based, regularly request and update the same objects, and have changes performed by a single Java application with multiple, distributed sessions.

As an alternative to cache coordination, you can tune the TopLink cache for each read-only, read-mostly, and write-mostly classes using identity type, cache invalidation, or cache isolation. You can perform this tuning before cache coordination.

13.7.1.7 Cache Isolation

Isolated client sessions provide a mechanism for disabling the shared server session cache. Any classes marked as isolated only cache objects relative to the life cycle of their client session. These classes never utilize the shared server session cache. This is the best mechanism to prevent caching as it is configured on a per-class basis allowing caching for some classes, and denying it for others.

13.7.1.8 Cache Locking and Transaction Isolation

By default, TopLink optimizes concurrency to minimize cache locking during read or write operations. Use the default TopLink transaction isolation configuration unless you have a very specific reason to change it.

13.7.2 How to Configure the TopLink Cache

In JDeveloper, you can configure the TopLink cache for a specific TopLink map. The cache options will apply globally to all descriptors. You can override the map-level cache configuration by defining cache configuration at the descriptor level.

To configure the TopLink cache at the TopLink map-level:

  1. Select the TopLink map in the Application Navigator.

  2. In the Structure window, select the TopLink map.

  3. Complete the Caching files on the Defaults tab.

The TopLink cache is an in-memory repository that stores recently read or written objects based on class and primary key values.

To configure the TopLink cache at the descriptor-level:

  1. Select the TopLink map in the Application Navigator.

  2. In the Structure window, select the TopLink map.

  3. Complete the Caching files on the Caching tab.

13.7.3 Using Queries

TopLink enables you to create, read, update, and delete persistent objects or data using queries in both Java EE and non-Java EE applications for both relational and nonrelational data sources. For more information about queries, see the Oracle Fusion Middleware Developer's Guide for Oracle TopLink.

Querying a data source means performing an action on, or interacting with, the contents of the data source. To do this, perform the following:

  • Define an action in a syntax native to the data source being queried.

  • Apply the action in a controlled fashion.

  • Manage the results returned by the action (if any).

For TopLink, you must also consider how the query affects the TopLink cache.

13.7.3.1 TopLink Query Languages

TopLink enables you to express a query using any of the following query languages:

  • SQL Queries

  • EJBQL Queries

  • JPQL Queries

  • XML Queries

  • EIS Interactions

  • Query-by-Example

  • TopLink Expressions

13.7.3.2 TopLink Query Types

  • Named Queries – An instance of DatabaseQuery stored by name in a Session or a descriptor's DescriptorQueryManager where it is constructed and prepared once. Such a query can then be repeatedly executed by name.

  • Call Queries – An instance of Call that you create and then either execute directly, using a special Session API to perform limited data source actions on data only, or execute indirectly in the context of a DatabaseQuery. TopLink supports Call instances for custom SQL, stored procedures, and EIS interactions.

  • Descriptor Query Manager – The DescriptorQueryManager defines a default DatabaseQuery for each basic data source operation (create, read, update, and delete), and provides an API with which you can customize either the DatabaseQuery or its Call.

  • EJB 2.n CMP Finders – A query defined on the home interface of an enterprise bean that returns enterprise beans. You can implement finders using any TopLink query type, including JPAQLCall and EJBQLCall, a call that takes JPA/EJB QL.

In most cases, you can compose a query directly in a given query language or, preferably, you can construct a DatabaseQuery with an appropriate Call and specify selection criteria using a TopLink Expression. Although composing a query directly in SQL appears to be the simplest approach (and for simple operations or operations on unmapped data, it is), using the DatabaseQuery approach offers the compelling advantage of confining your query to your domain object model and avoiding dependence on data source schema implementation details.

13.7.4 How to Create Queries

Some queries are implicitly constructed for you based on passed in arguments and executed in one step (for example, session queries) and others you create explicitly, configure, and then execute, such as database queries.

To create a query:

  1. Select the TopLink map in the Application Navigator.

  2. In the Structure window, select the descriptor.

  3. On the Queries tab, create your desired query.

    The Queries tab allows you to create and manage queries associated with a TopLink descriptor. You can create a named query in the Named Queries section, or create a custom query in the Custom Calls section.

13.7.5 Using Basic Query API

The TopLink basic query API includes support for the following, most commonly used queries:

  • Session Queries

  • DatabaseQuery Queries

  • Named Queries

  • SQL Calls

  • EJBQL Calls

  • EIS Interactions

  • Collection Query Results

  • Report Query Results

13.7.6 Using Advanced Query API

The TopLink query API also allows the use of the following, more advanced query API calls and techniques:

  • Redirect Queries

  • Historical Queries

  • Fetch Groups

  • Read-Only Queries

  • Interfaces

  • Inheritance Hierarchy

  • Additional Join Expressions

  • EJB Finders

  • Cursor and Stream Query Results

For more information about advanced query API, see the Oracle Fusion Middleware Developer's Guide for Oracle TopLink.

13.7.6.1 Redirect Queries

A redirect query is a named query that delegates query execution control to your application. redirect queried allow you to define the query implementation in code as a static method. To perform complex operations, you can combine query redirectors with the TopLink query framework.

13.7.6.2 Historical Queries

To make a query time-aware, you specify an AsOfClause that TopLink appends to the query. Use the AsOfClause class if your historical schema is based on time stamps or the AsOfSCNClause class if your historical schema is based on database system change numbers. You can specify an AsOfClause at the time you acquire a historical session so that TopLink appends the same clause to all queries, or you can specify an AsOfClause on a query-by-query basis.

13.7.6.3 Fetch Groups

You can use a fetch group with a ReadObjectQuery or ReadAllQuery. When you execute the query, TopLink retrieves only the attributes in the fetch group. TopLink automatically executes a query to fetch all the attributes excluded from this subset when and if you call a getter method on any one of the excluded attributes.

13.7.6.4 Read-Only Queries

In cases where you know that data is read-only, you can improve performance by specifying a query as read-only: this tells TopLink that any object returned by the query is immutable.

You can configure an object-level read query as read-only. When you execute such a query in the context of a UnitOfWork, TopLink returns a read-only, non-registered object. You can improve performance by querying read-only data in this way because the read-only objects need not be registered or checked for changes.

13.7.6.5 Interfaces

When you define descriptors for an interface to enable querying, TopLink supports querying on an interface, as follows:

  • If there is only a single implementor of the interface, the query returns an instance of the concrete class.

  • If there are multiple implementors of the interfaces, the query returns instances of all implementing classes.

13.7.6.6 Inheritance Hierarchy

When you query on a class that is part of an inheritance hierarchy, the session checks the descriptor to determine the type of the class, as follows:

  • If you configure the descriptor to read subclasses (the default configuration), the query returns instances of the class and its subclasses.

  • If you configure the descriptor not to read subclasses, the query returns only instances of the queried class, but no instances of the subclasses.

  • If you configure the descriptor to outer-join subclasses, the query returns instances of the class and its subclasses.

  • If you configure the descriptor to outer-join subclasses, the query returns instances of the class and its subclasses.

13.7.6.7 Additional Join Expressions

You can set the query manager to automatically append an expression to every query it performs on a class. For example, you can add an expression that filters the database for the valid instances of a given class. Use this to do the following:

  • Filter logically deleted objects

  • Enable two independent classes to share a single table without inheritance

  • Filter historical versions of objects

13.7.6.8 EJB Finders

To create a finder for an entity bean that uses the TopLink query framework, you must define, declare, and configure it. For predefined finders, you do not need to explicitly create a finder. For default finders, you only need to define the finder method.

13.7.6.9 Cursor and Stream Query Results

Cursors and streams are related mechanisms that let you work with large result sets efficiently. A stream is a view of a collection, which can be a file, a device, or a Vector. A stream provides access to the collection, one element at a time in sequence. This makes it possible to implement stream classes in which the stream does not contain all the objects of a collection at the same time.

Large result sets can be resource-intensive to collect and process. To improve performance and give the client more control over the returned results, configure TopLink queries to use a cursor or stream. Cursors & streams are supported by all subclasses of DataReadQuery and ReadAllQuery.

13.7.7 How to Create TopLink Expressions

TopLink expressions let you specify query search criteria based on your domain object model. When you execute the query, TopLink translates these search criteria into the appropriate query language for your platform.

TopLink provides the following two public classes to support expressions:

  • The Expression class represents an expression that can be anything from a simple constant to a complex clause with boolean logic. You can manipulate, group, and integrate expressions.

  • The ExpressionBuilder class is the factory for constructing new expressions. You can specify a selection criterion as an Expression with DatabaseQuery method setSelectionCriteria and in a finder that takes an Expression.

A simple expression usually consists of the following parts:

  • The attribute, which represents a mapped attribute or query key of the persistent class.

  • The operator, which is an expression method that implements boolean logic, such as GreaterThan, Equal, or Like.

  • The constant or comparison, which refers to the value used to select the object.

To create basic expressions for use in named queries:

  1. Select the TopLink map in the Application Navigator.

  2. In the Structure window, select the descriptor.

  3. Select the named query and in the Selection Criteria area, edit the expression.

13.7.8 Understanding TopLink Transactions

A database transaction is a set of operations (create, update, or delete) that either succeed or fail as a single operation. The database discards, or rolls back, unsuccessful transactions, leaving the database in its original state. Transactions may be internal (that is, provided by TopLink) or external (provided by a source external to the application, such as an application server).

In TopLink, transactions are contained in the unit of work object. You acquire a unit of work from a session and using its API, you can control transactions directly or through a Java 2 Enterprise Edition (Java EE) application server transaction controller such as the Java Transaction API (JTA).

As a transaction is committed, the database maintains a log of all changes to the data. If all operations in the transaction succeed, the database allows the changes; if any part of the transaction fails, the database uses the log to roll back the changes.

Transactions execute in their own context, or logical space, isolated from other transactions and database operations. The transaction context is demarcated; that is, it has a defined structure that includes the following:

  • A begin point, where the operations within the transaction begin. At this point, the transaction begins to execute its operations.

  • A commit point, where the operations are complete and the transaction attempts to formalize changes on the database.

The degree to which concurrent (parallel) transactions on the same data are allowed to interact is determined by the level of transaction isolation configured. ANSI/SQL defines four levels of database transaction isolation. Each offers a trade-off between performance and resistance from the following unwanted actions:

  • Dirty read: a transaction reads uncommitted data written by a concurrent transaction.

  • Nonrepeatable read: a transaction rereads data and finds it has been modified by some other transaction that was committed after the initial read operation.

  • Nonrepeatable read: a transaction rereads data and finds it has been modified by some other transaction that was committed after the initial read operation.

13.7.9 TopLink Transactions and the Unit of Work

The unit of work isolates changes in a transaction from other threads until it successfully commits the changes to the database. Unlike other transaction mechanisms, the unit of work automatically manages changes to the objects in the transaction, the order of the changes, and changes that might invalidate other TopLink caches. The unit of work manages these issues by calculating a minimal change set, ordering the database calls to comply with referential integrity rules and deadlock avoidance, and merging changed objects into the shared cache. In a clustered environment, the unit of work also synchronizes changes with the other servers in the coordinated cache.

Like any transaction, a unit of work transaction provides the following:

  • Unit of Work Transaction Context – Unit of work operations occur within a unit of work context, in which writes are isolated from the database until commit time. The unit of work executes changes on copies, or clones, of objects in its own internal cache, and if successful, applies changes to objects in the database and the session cache.

  • Unit of Work Transaction Demarcation – In a TopLink application, your application demarcates transactions using the unit of work. If your application includes a Java EE container that provides container-managed transactions, your application server demarcates transactions using its own transaction service. You can configure TopLink to integrate with the container's transaction service by specifying a TopLink external transaction controller.

  • Unit of Work Transaction Isolation – The unit of work does not directly participate in database transaction isolation. Because the unit of work may execute queries outside the database transaction, the database does not have control over this data and its visibility. However, by default, TopLink provides a degree of transaction isolation regardless of database transaction isolation configured on the underlying database. Each unit of work instance operates on its own copy (clone) of registered objects. In this case, because the unit of work provides an API that allows querying to be done on object changes within a unit of work, the unit of work provides read committed operations. Changes are committed to the database only when the unit of work commit method is called.