Fusion Middleware Documentation
Advanced Search


Developing Applications with Oracle JDeveloper
Close Window

Table of Contents

Show All | Collapse

20 Developing Persistence in Applications Using Oracle TopLink

This chapter describes how to use the visual tools in JDeveloper to implement persistence using Oracle TopLink. You can configure TopLink descriptors and mappings for Java classes, EJBs, and JPA entities to data source elements (such as database tables or XML schema elements).

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:

20.1 About Developing Persistence in Applications Using TopLink

Oracle TopLink is an object-persistence and object-transformation framework that provides development tools and run-time capabilities.

TopLink links object-oriented programs with data structures. TopLink transforms object-oriented data into either relational data or XML documents. Using TopLink, you can integrate persistence and object-transformation into your application.

Using the tools in JDeveloper, you can configure and map Java classes, EJBs, and JPA entities to different data sources, including relational databases, enterprise information systems (EIS), XML schemas, and JSON documents. TopLink supports multiple standards, including JPA, JAXB, and Java EE.

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

20.2 Developing TopLink JPA Projects

The Java Persistence API (JPA) is a lightweight framework for Java persistence based on Plain Old Java Objects (POJOs). JPA is part of the EJB 3.x 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.

Oracle TopLink provides a complete, JPA 1.0 and 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.x container or outside the container. This includes Web containers, other non-EJB 3.x 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.x container.

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

20.2.1 How to Specify the JPA Version

You can specify which version of JPA (1.0 or 2.0) to use at the project level. If you create a new mappings file, a new persistence unit, or a new persistence descriptor (persistence.xml), and the JPA version has not been selected yet, you have the opportunity to select the version. If one of those items has already been created in the project, the version for the project is used.

To Specify the JPA Version:

  1. In a project that has not yet been associated with a JPA version, create any of the following:

  2. Select the JPA version:

    • On the Version page of the Create Entity wizard or the Create Entities from Tables wizard, select JPA 1.0 (Java EE 5) or JPA 2.0 (Java EE 6).

    • In the New Persistence Unit dialog or the New JPA Persistence Descriptor dialog, under JPA Version, select JPA 1.0 or JPA 2.0.

20.2.2 How to Create Entities

Starting with EJB 3.x, a JPA entity is a Plain Old Java Object (POJO) that represents persistent data stored in a relational database or other data store. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. In JDeveloper, you can create an entity by specifying all the pertinent information, including details about the table structure in the database. You can also create entities from existing database tables.

If no persistence configuration (persistence.xml) yet exists in the project, a new one is created.

When you create entities from tables, mappings are automatically created, which can later be modified.

To create an entity:

  1. In the Applications window, right-click the project in which you want to create an entity and choose New.

  2. In the New Gallery, expand Business Tier, select TopLink/JPA and then select Entity, and click OK.

  3. Complete the fields in the Create Entity wizard.

To create entities from existing database tables:

  1. In the Applications window, right-click the project in which you want to create entities and choose New.

  2. In the New Gallery, expand Business Tier, select TopLink/JPA and then select Entities From Tables, and click OK.

  3. Complete the fields in the Create Entities From Tables wizard.

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

Use the persistence configuration file (persistence.xml) to configure the persistence context.

To create a persistence configuration:

  1. In the Applications window, right-click the project in which you want to create a JPA persistence descriptor and choose New.

  2. In the New Gallery, expand Business Tier, select TopLink/JPA and then select JPA Persistence Descriptor, and click OK.

  3. Complete the fields in New JPA Persistence Descriptor dialog to create a default persistence unit for the new JPA persistence descriptor file (persistence.xml) and click OK.

    Example 20-1 contains a sample persistence configuration.

Example 20-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="myPersistenceUnitName">
...
 </persistence-unit>
</persistence>

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

  1. In the Applications window, select the JPA Persistence descriptor (persistence.xml).

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

  3. On the JPA Persistence descriptor (persistence.xml) page, complete the General and Metadata Preferences tabs.

20.2.4 How to Create Persistence Units

To create a persistence unit:

  1. In the Applications window or Structure window, double-click the persistence descriptor (persistence.xml).

  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 20.2.8, "How to Create JPA Mapping Descriptors.")

    Example 20-2 contains a sample persistence unit.

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

20.2.5 How to Configure Persistence Units

The tabs of the Persistence Unit page (accessed by first selecting persistence.xml in the Applications window 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. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for the persistence unit, click the General navigation tab and then complete the fields to specify how the persistence unit connects to the application server and database.

To configure the connection information for a JPA persistence unit:

  1. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for the persistence unit, click the Connection navigation tab and then complete the fields 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. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for the persistence unit, click the Session Customization navigation tab and then complete the fields to specify TopLink-specific information for the persistence unit. You can specify entity customizer classes, set TopLink session overrides, and customize entity manager properties, for example, validation mode, pessimistic locking mode, and query timeout mode.

To configure the DDL generation options:

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

  1. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for the persistence unit, click the Schema Generation navigation tab and then complete the fields to specify how the TopLink generates the DDL scripts.

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

  1. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for persistence unit, click the Properties navigation tab and then complete the fields to specify the general, non-TopLink specific properties.

To configure metadata overrides for a persistence unit:

  1. In the Applications window, double-click the JPA persistence descriptor (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. Under Persistence Units, double-click the name of the persistence unit you want to configure.

  4. In the overview editor for the persistence unit, click the Metadata Preferences navigation tab and then complete the fields to specify the information for the mapping descriptor.

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

20.2.6 About Using JPA Mappings

TopLink supports the following mappings:

TopLink JPA supports the following types of mappings for an entity:

  • Basic - A basic mapping defines a direct association between an entity field/property and a column on the database.

  • Element collection - An element collection mapping maps an association collection of basic values or embeddables to the database.

  • Embedded - An embedded mapping is used to specify a persistence property of an entity whose value is an instance of an embeddable class.

  • Embedded ID - An embedded ID mapping designates a persistent field or property of an entity or mapped superclass which is a composite primary key that is an embeddable class. The referenced embeddable class must be an Embeddable.

  • ID - An ID mapping designates the primary key property or field of an entity and may be applied in an entity or mapped superclass.

  • Many-to-many - By default, JPA automatically defines a many-to-many mapping for a many-valued association with many-to-many multiplicity.

  • Many-to-one - By default, JPA defines a many-to-one mapping for a single-valued association to another entity that has many-to-one multiplicity.

  • One-to-many - A many-to-one mapping defines a many-valued association with one-to-many multiplicity. Bidirectional and unidirectional mappings are supported.

  • One-to-one - A one-to-one mapping defines a single-valued association to another entity that has one-to-one multiplicity. Bidirectional and unidirectional mappings are supported.

  • Transformation - A transformation mapping is used to map an attribute to one or more database columns. A read transformer and multiple write transformers can be configured.

  • Transient - By default, all fields of an entity are assumed to be persistent. Use a transient mapping to specify a field or property of an entity that is not persistent, for example a field or property that is used at run time but that is not part of the entity's state.

  • Variable one-to-one - A variable one-to-one mapping is used to represent a pointer reference between a Java object and an implementer of an interface. This mapping is usually represented by a single pointer (stored in an instance variable) between the source and target objects.

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

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

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

20.2.6.4 Configuring an Entity

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

20.2.6.5 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. A basic mapping defines a direct association between an entity field/property and a column on the database. By default, TopLink persistence provider automatically configures a basic mapping for simple types. However, you can use the @Basic annotation to override defaults.

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

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

20.2.6.8 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

20.2.7 How to Use JPA Mappings

The following procedures describe how to accomplish various tasks when working with JPA mappings.

To configure mappings using annotations:

  1. In the Applications window, select the persistence configuration (persistence.xml).

  2. In the Structure view, open the nodes down to the level of the mappings. That is, expand the project, expand the mapped classes, then expand the entity.

  3. Do either of the following:

    • Select the field or property (for example, CountryID). In the Overview editor for the mapping, edit the details of the mapping, as desired.

    • Right-click the field or property, point to Map As, then choose a new mapping. In the Overview editor for the mapping, edit the details of the mapping, as desired.

  4. To view the Java source, right-click the mapped field or property in the Structure view, and click Go to Source.

To configure mappings using a mapping descriptor file (orm.xml):

  1. In the Applications window, select the mapping descriptor (orm.xml).

  2. In the Structure view, open the nodes down to the level of the mappings. That is, expand the project, expand the mapped classes, then expand the entity.

  3. Do either of the following:

    • Select the field or property (for example, CountryID). In the Overview editor for the mapping, edit the details of the mapping, as desired.

    • Right-click the field or property, point to Map As, then choose a new mapping. In the Overview editor for the mapping, edit the details of the mapping, as desired.

  4. To view the XML source:

    1. Right-click the mapped field or property in the Structure view, and click Go to Source.

    2. If the Overview editor for the mapping is displayed, click the Source tab to see the XML source.

20.2.8 How to Create JPA Mapping Descriptors

The JPA mapping descriptor (typically named orm.xml) can be used as an alternative to annotations. Information in the JPA mapping descriptor overrides the Java annotations.

To create JPA mapping descriptors:

  1. In the Applications window, right-click the project in which you want to create a JPA persistence descriptor and choose New.

  2. In the New Gallery, expand Business Tier, select TopLink/JPA and then select JPA Mapping (XML), and click OK.

  3. Complete the fields in New JPA Mappings dialog and click OK.

To create JPA mapping descriptors associated with a persistence unit:

  1. In the Applications window, double-click the persistence configuration (persistence.xml).

  2. In the overview editor for persistence.xml, click the General navigation tab.

  3. In the Persistence Units area, double-click the persistence unit.

  4. Click the General tab for the persistence unit,

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

  6. Complete the fields in the dialog and click OK.

  7. In the JPA Mapping Descriptors area, double-click the name of the new mapping descriptor and then specify the details for the descriptor (such as mapped classes, development database, and other defaults).:

To configure the general information for a JPA mapping descriptor:

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the General navigation tab, and then complete the fields to select a persistence provider and configure its general properties (such as mapped classes, development database, and other defaults).

To associate entities, embeddables, or mapped classes with a JPA mapping descriptor:

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. in the Overview editor for the descriptor, click the General navigation tab.

  3. In the Mapped Classes area, do any of the following:

    • Under Entities, click the Add Classes as Entities icon.

    • Under Embeddables, click the Add Classes as Embeddable Classes icon.

    • Under Mapped Superclasses, click the Add Classes as Mapped Superclasses icon.

  4. In the Manage Entity Classes dialog, the Manage Embeddable Classes dialog, the Manage Mapped Superclasses Classes dialog, do the following:

    1. Select the project.

    2. Under Available Classes, expand the node and select the items to add.

    3. Click the Add Selected Classes to List or Add All Classes to List icon to move the selected items to the Selected Classes list. Then click OK.

20.2.8.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. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the Persistence Unit Defaults navigation tab and then complete the fields to configure the access type, entity listeners, multitenancy, delimited identifiers, and other defaults.

20.2.8.2 How to Set Access Type Defaults and Overrides

You can specify whether the persistent state of managed class attributes is accessed on fields or properties. Field values are accessed directly, and property values are accessed using get() and set() methods.

You can set defaults or specify specific access types at various levels in the configuration. Using defaults and overrides is sometimes called "mixed access."

By default, a single access type (field or property) applies to an entity hierarchy, although the default can be overridden, as described in the following sections.

The order of precedence of access type settings is described in the following list, from highest precedence to lowest. For managed classes (entities, embeddables, and mapped superclasses), the setting for a class or an attribute lower in an inheritance hierarchy overrides the setting higher in the hierarchy.

  1. Mapped attribute. A setting at this level overrides the default settings on managed classes, mapping descriptors (orm.xml), and persistence units.

  2. Managed classes. A setting at this level overrides the default settings for mapping descriptors (orm.xml) and persistence units. It can be overridden by settings on mapped attributes.

    The access type of an embeddable class is determined by the access type of the entity class, mapped superclass, or embeddable class in which it is embedded (including as a member of an element collection) independent of whether the access type of the containing class has been explicitly specified or defaulted. You can override the inherited access type by specifying a different type for the embeddable class.

  3. Mapping descriptors (orm.xml). A setting at this level overrides the default settings for the persistence unit. It can be overridden by settings on managed classes and mapped attributes.

  4. Persistence units. A setting at this level can be overridden by settings for mapping descriptors, managed classes, and mapped attributes.

To configure access type for managed classes in the persistence unit:

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the Persistence Unit Defaults navigation tab.

  3. Under Access Type, select Field Accessing or Method Accessing to define the default for all the managed classes in the persistence unit that have XML entries in the mapping descriptor.*

To configure access type for managed classes in the mapping descriptor:

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the General navigation tab.

  3. In the Defaults area, under Access Type, select Field or Property.

To configure access type for a managed class (entity, embeddable class, or mapped superclass):

  1. In the Applications window, double-click the Java source file for the managed class).

  2. In the Overview editor for the class, click the General navigation tab.

  3. Under Access Type, select Field or Property

To specify method accessing for attribute mappings:

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the Structure window, expand the managed class containing the attribute mapping you want to configure, then double-click the attribute.

  3. Select Use Method Accessing, then select the desired set() and/or get() method.

20.2.9 How to Generate Unique IDs for Primary Keys

Define generators to determine the generator strategy for an entity and the named generator be used to assign a unique ID to an entity. The scope of a generator name is global to the persistence unit across all generator types. A generator defined using XML in a mapping descriptor overrides a generator of the same name defined using an annotation on an entity.

To configure generators in the JPA mapping descriptor (orm.xml):

  1. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the Generators tab to configure sequence generators and table generators.

To configure generators for entities

  1. In the Applications window, double-click the source file for the entity, for example Departments.java.

  2. In the overview editor for the entity, click the Generators tab to configure sequence generators and table generators.

20.2.10 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. In the Applications window, double-click the JPA mapping descriptor (orm.xml).

  2. In the overview editor for the mapping descriptor, click the Queries navigation tab to define named queries, named native queries, and named stored procedure queries.

20.2.11 How to Specify Derived Identifiers in Mappings

In one-to-one and many-to-one mappings, you can specify that the identity (Id) for an entity is derived from the Id of its parent entity (the target of the mapping).

To specify that an identifier Is derived:

  1. In the Applications window, click the configuration file that specifies the mappings, persistence.xml or the JPA mapping descriptor (orm.xml).

  2. In the Structure window, expand the class containing the one-to-on or many-to-one mapping for which you want to specify a derived identifier, then click the attribute.

  3. Select Derived Identity, then select one of the following:

    • None - Do not derive an Id.

    • Id - Select if the Id is a single value, in which case the source object's Id is the same as the target object's Id.

    • Maps Id - Select an attribute to provide the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity.

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

20.3 Developing Native TopLink Mappings

Using the tools in JDeveloper, you can use native TopLink to configure and map Java classes, EJBs, and JPA entities to different data sources, including relational databases, enterprise information systems (EIS), and XML schemas. TopLink supports multiple standards, including JPA, JAXB, and Java EE.

20.3.1 Designing Native TopLink Applications

You can use native native 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 Oracle WebLogic Server or Apache Tomcat

  • Java clients such as Java SE and web browsers

20.3.2 Using Native TopLink in Application Design

Native TopLink can be used in the following ways:

  • Relational Database Usage: You can use native 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 native 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 native 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).

20.3.3 Creating Native TopLink Metadata

Native 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, TopLink JPA annotation extensions, and TopLink property extensions. The TopLink JPA persistence provider interprets these sources of metadata to create an in-memory 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 or JPA entities) and the code written with the TopLink API, to complete the application.

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

20.3.4 Creating Project Metadata

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

20.3.5 Creating Session Metadata

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

20.3.6 Using Native 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

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

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

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

20.3.7 Using Native TopLink Mappings

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

20.3.7.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 20-1 illustrates the relational mapping types build maps using the TopLink concepts of directionality, transformers, converters, and EJB 2.n CMP relational mapping.

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


20.3.7.2 EIS Mapping Types

Native 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 20-2 illustrates the EIS mapping types that TopLink provides:

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


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


20.3.8 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.1 JPA.

The TopLink editor displays the information or properties specific to the element selected in the Applications window or the Structure view. For example, selecting TopLink project elements in the Applications window, 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.

20.3.8.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 Applications window 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.

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.

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

20.3.8.3 Managing Persistence Configurations

The TopLink editor enables you to configure the persistence.xml file, which packages entities in TopLink JPA projects. By choosing Applications window 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.

20.3.8.4 The TopLink Structure View Toolbar

The Structure view displays detailed information about the TopLink element selected in the Applications window 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 20-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.


20.3.8.5 TopLink Project Elements in the Applications window

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

TopLink project elements in the Applications window may include:

  • TopLink folder

  • Sessions configuration file (sessions.xml)

  • TopLink map (tlMap)

20.3.8.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 Applications window or Structure view.

20.3.8.7 TopLink Project Elements in the Structure View

The Structure view displays detailed information about the TopLink element selected in the Applications window 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 Applications window 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.

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

20.3.8.9 TopLink Mapping Status Report in Message Log

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

20.3.8.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. From the main menu, choose Tools > Preferences.

  2. In the Categories list, expand TopLink Customization.

  3. Configure JPA and Query options.

  4. Complete each field and click OK.

20.3.8.11 How to Create a Native TopLink Mapping Project

JDeveloper stores the native TopLink descriptors (for more information, see Section 20.3.6, "Using Native TopLink Descriptors") and mappings (for more information, see Section 20.3.7, "Using Native 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 add a Native TopLink Object Map to an existing project:

  1. In the Applications window, right-click the project to which you want to add a TopLink map and choose New.

  2. In the New Gallery, expand Business Tier, select TopLink/JPA then select TopLink Object Map, and click OK.

  3. Complete each field and click OK.

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

20.3.8.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 Applications window, select a TopLink map.

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

  3. Follow the steps in the Automap Wizard.

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

20.4 Developing Native 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.

20.4.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 native TopLink object map for a relational project:

  1. If you are creating a new project for the relational project, create a new project, as follows:

    1. From the main menu, elect File > New > Project.

    2. In the New Gallery, select Projects > Custom Project.

  2. In the Applications window, right-click the project in which you want to create a TopLink object map and choose New > From Gallery.

  3. In the New Gallery, expand Business Tier, select TopLink/JPA and then select TopLink Object Map.

  4. Click OK.

  5. In the Data Source area of the New TopLink Object Map dialog, select Database, then specify your database information.

  6. Click OK.

    The new project includes the TopLink map and a TopLink sessions configuration file (sessions.xml).

20.4.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 20.4.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. In the Applications window, right-click the TopLink map and then select Add or Remove Descriptors.

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

    The descriptors are added to the TopLink map in the Structure window.

20.4.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. In the Applications window, select the TopLink map.

  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.

20.5 Developing Native 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.

20.5.1 How to Create XML Projects and Object Maps

To create a new native TopLink object map for an XML project:

  1. If you are creating a new project for the XML project, create it as follows:

    1. From the main menu, elect File > New > Project.

    2. In the New Gallery, select Projects > Custom Project.

  2. In the Applications window, right-click the project in which you want to create the TopLink XML object map and choose New > From Gallery.

  3. In the New Gallery, expand Business Tier, select TopLink/JPA and then select TopLink Object Map.

  4. Click OK.

  5. In the Data Source area of the New TopLink Object Map dialog, select XML.

  6. Click OK.

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

20.5.2 How to Create XML Descriptors

To create new TopLink descriptors for an XML project:

  1. Right-click the TopLink map in the Applications window 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.

20.5.3 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. In the Applications window, select the TopLink map.

  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.

20.6 Developing Native 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:

  • Using a specialized JDBC driver that allows connecting to an EIS system as if it were a relational database. You could use a TopLink relational project with these drivers.

  • Linking to or integrating with the EIS data from a relational database, such as Oracle Database.

  • Using a proprietary API to access the EIS system. In this case it may be possible to wrap the API with a JCA CCI interface to allow usage with a TopLink EIS project.

20.6.1 How to Create EIS Projects and Object Maps

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.

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

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

  1. If you are creating a new project for the EIS project, create it as follows:

    1. From the main menu, elect File > New > Project.

    2. In the New Gallery, select Projects > Custom Project.

  2. In the Applications window, right-click the project in which you want to create a TopLink object map and choose New > From Gallery.

  3. In the New Gallery, expand Business Tier, select TopLink/JPA and then select TopLink Object Map.

  4. Click OK.

  5. In the Data Source area of the New TopLink Object Map dialog, select EIS, then specify your EIS platform.

  6. Click OK.

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

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

20.6.3 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 Advanced Queuing (AQ)

  • Attunity Connect

  • IBM MQSeries

  • Java Message Service (JMS)

  • Sun Blackbox

  • XML file

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

20.7 Developing Native TopLink Sessions

Each TopLink map belongs to a TopLink 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:

  • Server and Client Sessions – Server sessions provide session management to a single data source (including shared object cache and connection pools) for multiple clients in a three-tier architecture using database or EIS platforms. This is the most flexible, scalable, and commonly used session. You acquire a client session from a server session at run time to provide access to a single data source for each client.

  • Database Session – A database session provides a client application with a single data source connection, for simple, standalone applications in which a single connection services all data source requests for one user.

  • Session Broker and Client Sessions – A session broker provides session management to multiple data sources for multiple clients by aggregating two or more server sessions (can also be used with database sessions).

    You acquire a client session from a session broker at run-time to provide access to all the data sources managed by the session broker for each client.

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.

20.7.1 How to Create a New Native TopLink Sessions Configuration File

Each native 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 the Applications window, 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.

20.7.2 How to Create Native TopLink Sessions

A native 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 Applications window, 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.

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

20.7.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 Applications window, 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.

20.7.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. In the Applications window, select the TopLink sessions configuration (sessions.xml).

  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. If a login type has not yet been set for the session, select the type from the list:

    • Database - Select to configure connection information at the session level for a non-CMP TopLink application. The TopLink runtime uses this information whenever you perform a persistence operation using the session in your non-CMP TopLink application.

    • EIS - Select to configure connection information at the session level for an XML application. The TopLink runtime uses this information whenever you perform a persistence operation using the session in your EIS application.

    • XML - Use this page to specify the data source login settings for the TopLink XML session.

    For information about the options on the Login pages for Database, EIS, and XML, display the page (as described above) and press F1 to consult the online help.

20.7.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. In the Applications window, select the TopLink sessions configuration (sessions.xml).

  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.

20.8 Developing Native 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.

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

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

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

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

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

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

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

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

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

20.8.2 How to Configure the TopLink Cache

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

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. In the Applications window, select the TopLink map.

  2. In the Structure window, double-click the TopLink map.

  3. Select the Defaults tab.

  4. Under Caching, set the caching options. You can select the following types of caching: Full, None, Soft, Weak, Weak with Hard Subcache, and Weak with Soft Subcache. For information on these caching types and their options, press F1 and consult the online help.

To configure the TopLink cache at the descriptor level:

  1. In the Applications window, select the TopLink map.

  2. In the Structure window, expand the map to display its descriptors, then select the descriptor you want to configure.

  3. Select the Caching tab.

  4. Set the caching options. You can select the following types of caching: Full, None, Soft, Weak, Weak with Hard Subcache, and Weak with Soft Subcache. For information on these caching types and their options, press F1 and consult the online help.

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

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

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

20.8.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. In the Applications window, select the TopLink map.

  2. In the Structure window, select the descriptor.

  3. On the Queries tab, create the query.

    The Queries tab allows you to create and manage queries associated with a TopLink descriptor. Available actions are:

    • Named Queries: Create named queries of types ReadObjectQuery, ReadAllQuery, and ReportQuery.

    • Custom Calls: Create custom queries.

    • Query Keys: Query keys are schema-independent aliases for database field names and are supported in relational database projects only.

    • Settings: Set query time-outs and cache refresh options.

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

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

20.8.6.1 Redirect Queries

A redirect query is a named query that delegates query execution control to your application. Redirect queries 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.

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

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

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

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

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

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

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

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

20.8.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. In the Applications window, select the TopLink map.

  2. In the Structure window, select the descriptor.

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

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

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