2 Introduction to TopLink Application Development

This chapter describes how to build a TopLink application, including suggested development processes, architectures, and technologies.

This chapter includes the following sections:

2.1 Introduction to TopLink Application Development

To ensure the best design for your TopLink application, Oracle recommends that you follow an iterative step-by-step development process. The flexibility of TopLink lets you use any development tool.

This section describes following recommended development process:

2.1.1 Typical Development Stages

This section describes the general development stages of a TopLink application. Figure 2-1 illustrates the TopLink development process.

Figure 2-1 TopLink Development Process

Description of Figure 2-1 follows
Description of "Figure 2-1 TopLink Development Process"

Design the Application (1)

Define your application requirements, select an architecture, and determine the target platform. See Section 2.2, "Designing Your Application with TopLink" for more information. Remember, TopLink works with any architecture and any platform.

When designing the application, you should also create an object model for the application. See Section 2.8, "Persisting Objects" for more information. It is important to create the object model before using TopLink to map objects, because defining persistent mappings for an incorrect or rapidly changing model can be very difficult.

Develop the Application (2, 3, 4)

Create the Java classes and decide how the classes should be implemented by the data source. When working with a legacy system, decide how the classes relate to the existing data. If there is no legacy data source to integrate, decide how to store each class in the data source and create the required schema. Alternatively, you may use TopLink to create your initial tables.

Using Oracle JDeveloper TopLink Editor or TopLink Workbench, create descriptors and mappings for the persistent classes. Use TopLink sessions to manipulate the persistent classes, including querying and changing data. See Part II, "TopLink Development Tools Overview" for more information.

Avoid building all your model's descriptors in a single iteration. Start with a small subset of your classes. Build and test their descriptors, then gradually add new descriptors and relationships. This lets you catch common problems before they proliferate through your entire design.

Write Java code to use database sessions. Sessions are used to query for database objects and write objects to the database. See Chapter 87, "Introduction to TopLink Sessions" for more information.

Deploy the Application (5)

Generate, package, then deploy the necessary files to your application server. The required information will vary, depending on your environment and architecture. See Part III, "TopLink Application Deployment" for more information.

Maintain the Application (6)

TopLink includes many options that can enhance application performance. You can customize most aspects of TopLink to suit your requirements. Use advanced TopLink features or write custom querying routines to access the database in specific ways, and to optimize performance. See Part IV, "Optimization and Customization of a TopLink Application" for more information.

2.1.2 Oracle Development Support

Oracle provides additional support for you as a TopLink developer on the Oracle Technology Network (OTN), including the following:

  • Metalink support

  • Discussion forums

  • How-to documents

  • Examples

You must register online before using OTN; registration is free of charge and can be done at

http://www.oracle.com/technology/membership

If you already have a user name and password for OTN, then you can go directly to the documentation section of the OTN Web site at

http://www.oracle.com/technology/docs

Using your OTN user name and password, you can also access the TopLink developer's forum to post questions and get answers about using TopLink at

http://forums.oracle.com/forums/forum.jsp?forum=48

2.2 Designing Your Application with TopLink

When you design your application, you must choose how and where to use TopLink. You can use TopLink to perform a variety of persistence and data transformation functions (see Section 2.2.1, "How to Use TopLink in Your Application Design") on a variety of Java-supporting platforms (see Section 2.2.2, "Target Platforms"). When you design your application architecture, keep these capabilities in mind (see Section 2.3, "Selecting an Architecture with TopLink").

2.2.1 How to Use TopLink in Your Application Design

This section describes the basic ways in which you can use TopLink, including the following usage types:

2.2.1.1 Relational Database Usage

You can use TopLink to persist Java objects to relational databases that support SQL data types accessed using JDBC.

For more information, see Section 18.1.1, "How to Build Relational Projects for a Relational Database".

2.2.1.2 Object-Relational Data Type Database Usage

You can use TopLink to persist Java objects to object-relational data type databases that support data types specialized for object storage (such as Oracle Database) accessed using JDBC.

For more information, see Section 18.1.2, "How to Build Relational Projects for an Object-Relational Data Type Database".

2.2.1.3 Oracle XML Database (XDB) Usage

You can use TopLink to persist XML documents to an Oracle XML database using TopLink direct-to-XMLType mappings.

For more information, see Chapter 18, "Introduction to Relational Projects" and Section 27.4, "Direct-to-XMLType Mapping".

2.2.1.4 Enterprise Information System (EIS) Usage

You can use TopLink to persist Java objects to an EIS data source using a JCA adapter.

In this scenario, the application invokes EIS data source-defined operations by sending EIS interactions to the JCA adapter. Operations can take (and return) EIS records. Using TopLink EIS descriptors and mappings, you can easily map Java objects to the EIS record types supported by your JCA adapter and EIS data source.

This usage is common in applications that connect to legacy data sources and is also applicable to Web services.

For more information, see Chapter 71, "Introduction to EIS Projects".

2.2.1.5 XML Usage

You can use TopLink for in-memory, nonpersistent Java object-to-XML transformation with XML Schema (XSD) based XML documents and JAXB.

You can use the TopLink JAXB compiler with your XSD to generate both JAXB-specific artifacts (such as content and element interfaces, implementation classes, and object factory class) and TopLink-specific artifacts (such as sessions and project XML files and TopLink Workbench project). For more information, see Section 47.1.1, "TopLink Support for Java Architecture for XML Binding (JAXB)".

This usage has many applications, including messaging and Web services.

For more information, see Chapter 47, "Introduction to XML Projects".

2.2.2 Target Platforms

TopLink supports any enterprise architecture that uses Java, including the following:

  • Java EE

  • Spring

  • Java Web servers such as Tomcat

  • Java clients such as Java SE and Web browsers

  • Server Java platforms

Application packaging requirements of the specific target platform (for deployment in the host Java or Java EE environment) influences how you use and configure TopLink. For example, you package a Java EE application in an Enterprise Archive (EAR) file. Within the EAR file, there are several ways to package persistent entities within Web Archive (WAR) and Java Archive (JAR). How you configure TopLink depends, in part, on how you package the application and how you use the host application server class loader.

In addition, TopLink provides custom CMP integration for a variety of application servers.

For detailed information about supported application server versions, custom integration, and configuration requirements, see Chapter 8, "Integrating TopLink with an Application Server".

2.3 Selecting an Architecture with TopLink

This section describes some of the key aspects of application architecture that apply to TopLink and discusses the various options available for each, including the following:

2.3.1 Tiers

This section describes choices you need to make when deciding on how to separate client and server functionality in your application architecture.

These choices can be summarized as follows:

2.3.1.1 Three Tier

Oracle recommends a three-tier application architecture. With a three-tier architecture, Oracle recommends using EclipseLink JPA or server sessions and client sessions (see Section 87.3, "Server and Client Sessions") and the TopLink unit of work (see Chapter 113, "Introduction to TopLink Transactions").

For more information, see Section 2.11, "Considering Three-Tier Architecture".

2.3.1.1.1 Java EE or Non-Java EE

You can use TopLink in a Java EE or non-Java EE application architecture. Oracle recommends that you use a Java EE application architecture.

With a Java EE application, you should use external connection pools (see Section 96.1.6.2, "External Connection Pools"). You may consider using JPA or CMP, EJB session beans, and Java Transaction API (JTA) integration (see Section 113.1.2.1, "JTA Controlled Transactions").

With a non-Java EE application, you should use internal connection pools (see Section 96.1.6.1, "Internal Connection Pools"). You may still consider using JPA.

2.3.1.1.2 Client

In a three-tier application architecture, you can implement any of the following types of client:

  • Web client–Oracle recommends that you implement a Web client.

  • XML/Web service client–With this client type, you can use TopLink XML (see Section 2.2.1.5, "XML Usage").

  • Java (fat) client–With this client type, you can choose the means of communicating with the server:

    • EJB session beans–Oracle recommends this approach. You may consider using the UnitOfWork method mergeClone to handle merging deserialized objects (see Section 115.5, "Merging Changes in Working Copy Clones"). The disadvantage of this approach is that your application must handle serialization. Avoid serializing deep object graphs. You should use indirection, also known in JPA as lazy loading (see Section 121.3, "Configuring Indirection (Lazy Loading)"). Consider using the data-transfer-object pattern.

    • XML/Web service–Use TopLink XML (see Section 2.2.1.5, "XML Usage").

    • EJB entity bean–Use TopLink CMP integration or BMP support. The disadvantage of this approach is that remote entity beans may not perform or scale well.

    • RMI–You may consider using a TopLink remote session (see Section 87.9, "Remote Sessions"). The disadvantage of this approach is that a remote session is stateful and may not scale well.

See also Section 2.3.2, "Service Layer".

2.3.1.2 Two Tier

With a two-tier application architecture, Oracle recommends using TopLink database sessions (see Section 87.8, "Database Sessions") and the TopLink unit of work (see Chapter 113, "Introduction to TopLink Transactions"). The disadvantages of this architecture are that it is not Web-enabled and does not scale well to large deployments.

For more information, see Section 2.12, "Considering Two-Tier Architecture".

2.3.2 Service Layer

This section describes choices you need to make when deciding on how to encapsulate your application's business logic (or service).

These choices can be summarized as follows:

See also:

2.3.2.1 EJB Session Beans

Oracle recommends using EJB session beans.

With EJB session beans, you should use JTA integration (see Section 113.1.2.1, "JTA Controlled Transactions") and external connection pools (see Section 96.1.6.2, "External Connection Pools"). You should acquire a unit of work (see Section 115.13.1, "How to Acquire a Unit of Work with an External Transaction Service").

For more information, see Section 2.13, "Considering EJB Session Bean Facade Architecture".

2.3.2.1.1 Stateful

If you are using stateful session beans, then note that a reference to a client session cannot be passivated. In this case, you must reacquire a client session (see Section 87.2.4, "Acquiring a Session at Run Time with the Session Manager") on activate or per request.

2.3.2.1.2 Stateless

If you are using stateless session beans, you must acquire new client session (see Section 87.2.4, "Acquiring a Session at Run Time with the Session Manager") for each request.

2.3.2.2 EJB Entity Beans

EJB entity bean architectures are slightly different from other TopLink architectures, because the EJB entity bean interfaces hide TopLink functionality completely from the client application developer.

You can use entity beans in almost any Java EE application. For TopLink, how the application uses the entity beans is not important; how entity beans are mapped and implemented is important to TopLink.

2.3.2.2.1 Container-Managed Persistence (CMP)

Oracle recommends using entity beans with container-managed persistence. In this case, you should use the TopLink CMP integration for your application server. You must ensure that you are using a Java EE server that TopLink supports (see Chapter 8, "Integrating TopLink with an Application Server").

For more information, see Section 2.14, "Considering EJB Entity Beans with CMP Architecture".

2.3.2.2.2 Bean-Managed Persistence (BMP)

If you are using entity beans with bean-managed persistence, you should use the TopLink BMP integration. The disadvantages of this architecture are that the BMP architecture is restrictive and may not provide good performance.

For more information, see Section 2.15, "Considering EJB Entity Beans with BMP Architecture".

2.3.2.3 JPA Entities

Java Persistence API (JPA) is a specification for persistence in Java EE and Java SE applications. In JPA, a persistent class is referred to as an entity. An entity is a plain old Java object (POJO) class (see Section 2.3.2.4, "Plain Old Java Objects (POJO)") that is mapped to the database and configured for usage through JPA using annotations, persistence XML, or both.

With JPA, when your application is running inside a container, all of the benefits of the container support and ease of use apply. Note that you can configure the same application to run outside the container.

You can use session beans (see Section 2.3.2.1, "EJB Session Beans") as the means for your application to interact with JPA.

EclipseLink JPA is a standards-compliant JPA persistence provider built on the EclipseLink foundation library. EclipseLink JPA offers a variety of vendor extensions (annotations and persistence unit properties) that give you full access to the underlying EclipseLink API to take advantage of additional functionality and performance benefits.

For more information, see the following:

2.3.2.4 Plain Old Java Objects (POJO)

If you choose to build your service layer with non-EJB Java objects with a Java EE application server, you should use external connection pools (see Section 96.1.6.2, "External Connection Pools"). If you use a non-Java EE Web server, you should use internal connection pools (see Section 96.1.6.1, "Internal Connection Pools"). In either case, you may consider using JTA integration (see Section 113.1.2.1, "JTA Controlled Transactions").

2.3.3 Data Access

This section describes choices you need to make when deciding on what type of data your application architecture must support.

These choices can be summarized as follows:

See also Section 2.3.5, "Locking".

2.3.3.1 Data Type

You can use TopLink to manage any of the following types of data:

2.3.3.2 Multiple Data Sources

If your application architecture must access more than one data source, Oracle recommends that you use a session broker (see Section 87.7, "Session Broker and Client Sessions") and JTA integration (see Section 113.1.2.1, "JTA Controlled Transactions") for two-phase commit.

Alternatively, you may use multiple sessions.

2.3.3.3 Isolating Data Access

If your application architecture requires that some data be restricted to a private cache and isolated from the TopLink shared session cache, Oracle recommends that you use an isolated session (see Section 87.5, "Isolated Client Sessions"). You can also use an isolated session with the Oracle Virtual Private Database (VPD) feature (see Section 87.5.1, "Isolated Client Sessions and Oracle Virtual Private Database (VPD)").

2.3.3.4 Historical Data Access

If your data source maintains past or historical versions of objects, Oracle recommends that you use a TopLink historical session (see Section 87.6, "Historical Sessions") to access this historical data so that you can express read queries conditional on how your objects are changing over time.

2.3.4 Caching

This section describes choices you need to make when deciding on how to use the TopLink cache (see Chapter 102, "Introduction to Cache") in your application architecture.

These choices can be summarized as follows:

See also Section 2.3.5, "Locking".

2.3.4.1 Cache Type

Choose a cache type (see Section 102.2.1, "Cache Type and Object Identity") appropriate for the type of data your application processes. For example, consider a weak identity map for volatile data (see Section 102.2.1.6, "Guidelines for Configuring the Cache and Identity Maps").

2.3.4.2 Refreshing

Consider how your application architecture may be affected by stale data (see Section 102.2.3, "Handling Stale Data"): for example, consider using query or descriptor refresh options (see Section 2.3.4.2, "Refreshing") or cache invalidation (see Section 102.2.5, "Cache Invalidation"). Consider using an isolated session's cache (see Section 87.5, "Isolated Client Sessions") for volatile data.

Avoid using no identity map (seeSection 102.2.1.5, "No Identity Map") for objects that are involved in relationships or that require object identity.

2.3.4.3 Cache Coordination

TopLink provides a distributed cache coordination feature that allows multiple, possibly distributed, instances of a session to broadcast object changes among each other so that each session's cache is kept up to date (see Section 102.3, "Cache Coordination"). Before using cache coordination, ensure that it is appropriate for your application (see Section 102.3.1, "When to Use Cache Coordination").

2.3.4.3.1 Protocol

You can configure a coordinated cache to broadcast changes using any of the following communication protocols:

2.3.4.3.2 Synchronization

You can configure synchronization strategy that a coordinated cache uses to determine what it broadcasts when an object changes. You can configure this at the project (see Section 117.12, "Configuring Cache Coordination Change Propagation at the Project Level") or descriptor (Section 119.15, "Configuring Cache Coordination Change Propagation at the Descriptor Level") level as follows:

  • Invalidate changed objects–Propagate an object invalidation that marks the object as invalid in all other sessions. This tells other sessions that they must update their cache from the data source the next time this object is read. Oracle recommends using this synchronization strategy.

  • Synchronize changes–Propagate a change notification that contains each changed attribute.

  • Synchronize changes and new objects–Propagate a change notification that contains each changed attribute. For new objects, propagate an object creation (along with all the new instance's attributes).

2.3.5 Locking

This section describes choices you need to make when deciding on how to use TopLink locking options in your application architecture. Oracle strongly recommends always using a locking policy in a concurrent system (see Section 119.26, "Configuring Locking Policy").

These choices can be summarized as follows:

If you are building a three-tier application, be aware of how that architecture affects the way you use locking (see Section 16.4.6, "Locking in a Three-Tier Application").

For more information, see Section 16.4, "Descriptors and Locking".

2.3.5.1 Optimistic Locking

Oracle recommends using TopLink optimistic locking. With optimistic locking, all users have read access to the data. When a user attempts to write a change, the application checks to ensure the data has not changed since the user read the data.

You can use version (see Section 16.4.1, "Optimistic Version Locking Policies") or field (see Section 16.4.4, "Optimistic Field Locking Policies") locking policies. Oracle recommends using version locking policies.

2.3.5.2 Pessimistic Locking

With pessimistic locking, the first user who accesses the data with the purpose of updating it locks the data until completing the update. The disadvantage of this approach is that it may lead to reduced concurrency and deadlocks.

Consider using pessimistic locking support at the query level (see Section 119.7.1.9, "Configuring Named Query Options").

If are using CMP, you may consider using bean-level pessimistic locking support (see Section 119.7.1.9, "Configuring Named Query Options").

2.4 Building and Using the Persistence Layer

Oracle TopLink requires that classes must meet certain minimum requirements before they can become persistent. TopLink also provides alternatives to most requirements. TopLink uses a nonintrusive approach by employing a metadata architecture that allows for minimal object model intrusions.

This section includes the following information:

2.4.1 Implementation Options

When implementing your persistence layer using TopLink, consider the following options:

2.4.1.1 Using EclipseLink JPA Metatdata, Annotations, and XML

When using JPA, you can specify persistence layer components using any combination of standard JPA annotations and persistence.xml, EclipseLink JPA annotation extensions, and EclipseLink JPA persistence.xml extensions.

For more information, see Section 2.16, "Considering JPA Entity Architecture".

2.4.1.2 Using TopLink Metatdata XML

Persistence layer components may be generated as metadata from Oracle JDeveloper or TopLink Workbench.

Oracle recommends using Oracle JDeveloper or TopLink Workbench to create the necessary metadata (stored as XML). You can easily export and update the project.xml and sessions.xml files. This reduces development effort by eliminating the need to regenerate and recompile Java code each time you change the project. With Oracle JDeveloper or TopLink Workbench, you write Java code only for your own application classes and any necessary amendment methods. For information about the XML structure of the project.xml and sessions.xml files, refer to the appropriate XML schemas (XSD) in the TOPLINK_HOME/xsds directory.

TopLink Workbench provides Ant tasks that you can use to integrate TopLink Workbench with your automated builds.

For more information, see the following:

2.4.1.3 Using TopLink Metadata Java API

Persistence layer components may be coded or generated as Java from Oracle JDeveloper or TopLink Workbench.

To use Java code, you must manually write code for each element of the TopLink project including: project, login, platform, descriptors, and mappings. This may be more efficient if your application is model-based and relies heavily on code generation. Depending on the type of project you are creating, Oracle JDeveloper and TopLink Workbench can export Java code for projects, tables, and your model source.

TopLink Workbench provides Ant tasks that you can use to integrate TopLink Workbench with your automated builds.

For more information, see the following:

2.4.1.4 Using Method and Direct Field Access

You can access the fields (data members) of a class by using a getter/setter method (also known as property access) or by accessing the field itself directly.

When to use method or direct field access depends on your application design. Consider the following guidelines:

  • Use method access outside of a class.

    This is the natural public API of the class. The getter/setter methods handle any necessary side-effects and the client need not know anything about those details.

  • Use direct field access within a class to improve performance.

    In this case, you are responsible for taking into consideration any side-effects not invoked by bypassing the getter/setter methods.

When considering using method or direct field access, consider the following limitations.

If you enable change tracking on a getter/setter method (for example, you decorate method setPhone with @ChangeTracking), then TopLink tracks changes accordingly when a client modifies the field (phone) using the getter/setter methods.

Similarly, if you enable change tracking on a field (for example, you decorate field phone with @ChangeTracking), then TopLink tracks changes accordingly when a client modifies the field (phone) directly.

However, if you enable change tracking on a getter/setter method (for example, you decorate method setPhone with @ChangeTracking) and a client accesses the field (phone) directly, TopLink does not detect the change. If you choose to code in this style–field access within a class for performance and method access outside of a class –be aware of this limitation.

For more information, see the following:

2.4.1.5 Using Weaving

Weaving is a technique of manipulating the byte-code of compiled Java classes.

Weaving is used to enhance both JPA entities and Plain Old Java Object (POJO) classes for such things as lazy loading, change tracking, fetch groups, and internal optimizations.

For more information, see Section 2.10, "Using Weaving".

2.4.2 Persistent Class Requirements

The following requirements apply to plain Java objects:

  • You can use direct access on private or protected attributes. For more information on direct and method access, see Section 121.6, "Configuring Method or Direct Field Accessing at the Mapping Level".

  • When using nontransparent indirection, the attributes must be of the type ValueHolderInterface rather than the original attribute type. The value holder does not instantiate a referenced object until it is needed.

  • TopLink provides transparent indirection for Collection, List, Set, and Map attribute types for any collection mappings. Using transparent indirection does not require the use of the ValueHolderInterface or any other object model requirements.

If you are using weaving, the ValueHolderInterface is not required. For more information, see Section 2.4.1.5, "Using Weaving".

Note:

For EJB 2.0 entity beans with container-managed persistence, the bean requirements are defined by the EJB 2.0 specification; for EJB 2.1 entity beans with container-managed persistence, the bean requirements are defined by the EJB 2.1 specification.

See Section 17.2.4, "Indirection (Lazy Loading)" for more information on indirection and transparent indirection.

2.4.3 Persistence Layer Components

Typically, the TopLink persistence layer contains the following components:

2.4.3.1 Mapping Metadata

The TopLink application metadata model is based on the TopLink project. The project includes descriptors, mappings, and various policies that customize the run-time capabilities. You associate this mapping and configuration information with a particular data source and application by referencing the project from a session.

For more information, see the following:

2.4.3.2 Session

A session is the primary interface between the client application and TopLink, and represents the connection to the underlying data source.

TopLink offers several different session types (see Chapter 87, "Introduction to TopLink Sessions"), each optimized for different design requirements and architectures. The most commonly used session is the server session, a session that clients access on the server through a client session. The server session provides a shared cache and shared connection resources. You define a session with session metadata.

For CMP projects, the TopLink run-time creates and uses a session internally, but your application does not acquire or use this session directly. Depending on the application server you use, you can specify some of the parameters for this internal session.

For EclipseLink JPA projects, the EntityManager represents (wraps) the session.

For more information, see the following:

2.4.3.3 Cache

By default, a TopLink session provides an object-level cache that guarantees object identity and enhances performance by reducing the number of times the application needs to access the data source. TopLink provides a variety of cache options, including locking, refresh, invalidation, isolation, and coordination. Using cache coordination, you can configure TopLink to synchronize changes with other instances of the deployed application. You configure most cache options at the session level. You can also configure cache options on a per-query basis or on a descriptor to apply to all queries on the reference class.

For more information, see Chapter 102, "Introduction to Cache".

2.4.3.4 Queries and Expressions

TopLink provides several object and data query types, and offers flexible options for query selection criteria, including the following:

  • TopLink expressions

  • JPQL (Java Persistence Query Language)

  • SQL

  • Stored procedures

  • Query by example

With these options, you can build any type of query. Oracle recommends using predefined queries to define application queries. Predefined queries are held in the project metadata and referenced by name. This simplifies application development and encapsulates the queries to reduce maintenance costs.

When using entity beans, you can code finders completely using EJB QL (in addition to any of the other TopLink query options), enabling the application to comply with the Java EE specification.

Regardless of the architecture or persistent entity type, you are free to use any of the query options. Oracle JDeveloper and TopLink Workbench provide the simplest way to define queries. Alternatively, you can build queries in code, using the TopLink API.

For more information, see Chapter 108, "Introduction to TopLink Queries" and Chapter 110, "Introduction to TopLink Expressions".

2.4.3.5 Transactions

TopLink provides the ability to write transactional code isolated from the underlying database and schema by using a unit of work, a specific transactional session.

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.

If an application uses entity beans, you do not access the unit of work API directly, but you still benefit from its features: the integration between the TopLink runtime and the Java EE container automatically uses the unit of work to the application's best advantage.

For more information, see Chapter 108, "Introduction to TopLink Queries".

2.4.4 How to Use the Persistence Layer

At run time, your application uses the TopLink metadata (see Section 2.9, "Working with TopLink Metadata").

For a POJO (non-CMP) project, your application loads a session.xml file at run time using the session manager (see Chapter 90, "Acquiring and Using Sessions at Run Time"). The session.xml file contains a reference to the mapping metadata project.xml file. Using the session, your application accesses the TopLink runtime and the project.xml mapping metadata.

For a CMP project, the metadata required is dependent upon the Java EE application server you deploy your application to (see Chapter 9, "Creating TopLink Files for Deployment"). All application servers require an ejb-jar.xml and a TopLink project XML file. The session configuration is dependent on the specific Java EE application server.

2.5 Deploying the Application

Application packaging (for deployment in the host Java or Java EE environment) influences TopLink use and configuration. For example, you package a Java EE application in an EAR file. Within the EAR file, there are several ways to package persistent entities within WAR and JAR. How you configure TopLink depends, in part, on how you package the application and how you use the class loader of the host application server.

This section discusses packaging and deployment from a TopLink perspective. However, if you deploy your application to a Java EE container, you must configure elements of your application to enable TopLink container support.

This section includes the following information:

For more information, see Part III, "TopLink Application Deployment".

2.5.1 About Deployments

The TopLink approach to deployment involves packaging application files into a single file, such as aJAR file, or an EAR file. This approach lets you create clean and self-contained deployments that do not require significant file management.

After creating these files, deploy the project.

2.5.2 How to Use TopLink in a Java EE Application

Although TopLink is an integral part of a Java EE application, in most cases the client does not interact with TopLink directly. Instead, TopLink features are invoked indirectly by way of EJB container callbacks.

As a result, the typical deployment process involves the following steps:

  1. Build the project elements, including beans, classes, and data sources.

  2. Define the application mappings in Oracle JDeveloper TopLink Editor or TopLink Workbench.

  3. Build the application deployment files. Use Oracle JDeveloper or TopLink Workbench to create the files.

  4. Package and deploy the application.

  5. Add code to the client application to enable it to access the TopLink application.

2.6 Optimizing and Customizing the Application

TopLink provides a diverse set of features to optimize performance including the following:

  • Enhancing queries

  • Tuning the cache

  • Scaling to multiple server configuration

You enable or disable most features in the descriptors or session, making any resulting performance gains global.

Using TopLink EIS (see Section 2.2.1.4, "Enterprise Information System (EIS) Usage"), you can integrate a TopLink application with legacy data sources using a JCA adapter. This is the most efficient way to customize a TopLink application to accommodate unusual or nonstandard systems.

Using TopLink XML (see Section 2.2.1.5, "XML Usage"), you can integrate a TopLink application with legacy data sources using a Web service.

See Part IV, "Optimization and Customization of a TopLink Application" for details on optimizing and customizing TopLink.

2.7 Troubleshooting the Application

See Appendix A, "Troubleshooting a TopLink Application" for information on troubleshooting all aspects of a TopLink application including development and deployment.

2.8 Persisting Objects

This section includes a brief description of relational mapping and provides important information and restrictions to guide object and relational modeling. This information is useful when building TopLink applications.

This section includes information on the following:

These sections contain additional detail on these features, and explain how to implement and use them with TopLink.

2.8.1 Application Object Model

Object modeling refers to the design of the Java classes that represent your application objects. With TopLink, you can use your favorite integrated development environment (IDE) or Unified Modeling Language (UML) modeling tool to define and create your application object model.

Any class that registers a descriptor with a TopLink database session is called a persistent class. TopLink does not require that persistent classes provide public accessor methods for any private or protected attributes stored in the database. Refer to Section 2.4.2, "Persistent Class Requirements" for more information.

2.8.2 Data Storage Schema

Your data storage schema refers to the design that you implement to organize the persistent data in your application. This schema refers to the data itself–not the actual data source (such as a relational database or nonrelational legacy system).

During the design phase of the TopLink application development process (see Section 2.1.1, "Typical Development Stages"), you should decide how to implement the classes in the data source. When integrating existing data source information, you must determine how the classes relate to the existing data. If no legacy information exists to integrate, decide how you will store each class, then create the necessary schema.

You can also use Oracle JDeveloper (see Chapter 4, "Using Oracle JDeveloper TopLink Editor"), TopLink Workbench (see Chapter 5, "Using TopLink Workbench") or database schema manager (see Chapter 6, "Using the Schema Manager") to create the necessary information.

2.8.3 Primary Keys and Object Identity

When making objects persistent, each object requires an identity to uniquely identify it for storage and retrieval. Object identity is typically implemented using a unique primary key. This key is used internally by TopLink to identify each object, and to create and manage references. Violating object identity can corrupt the object model.

In a Java application, object identity is preserved if each object in memory is represented by one, and only one, object instance. Multiple retrievals of the same object return references to the same object instance–not multiple copies of the same object.

TopLink supports multiple identity maps to maintain object identity (including composite primary keys). Refer to Section 102.2.1, "Cache Type and Object Identity" for additional information.

2.8.4 Mappings

TopLink uses the metadata produced by Oracle JDeveloper or TopLink Workbench (see Section 2.9, "Working with TopLink Metadata") to describe how objects and beans map to the data source. This approach isolates persistence information from the object model–you are free to design their ideal object model, and DBAs are free to design their ideal schema.

You use Oracle JDeveloper or TopLink Workbench to create and manage the mapping information. At run time, TopLink uses the metadata to seamlessly and dynamically interact with the data source, as required by the application.

TopLink provides an extensive mapping hierarchy that supports the wide variety of data types and references that an object model might contain. For more information, see Chapter 17, "Introduction to Mappings".

2.8.5 Foreign Keys and Object Relationships

A foreign key is a combination of columns that reference a unique key, usually the primary key, in another table. Foreign keys can be any number of fields (similar to primary key), all of which are treated as a unit. A foreign key and the primary parent key it references must have the same number and type of fields.

Foreign keys represents relationships from a column or columns in one table to a column or columns in another table. For example, if every Employee has an attribute address that contains an instance of Address (which has its own descriptor and table), the one-to-one mapping for the address attribute would specify foreign key information to find an address for a particular Employee.

Refer to Section 28.7, "Configuring Table and Field References (Foreign and Target Foreign Keys)" for more information.

2.8.6 Inheritance

Object-oriented systems allow classes to be defined in terms of other classes. For example: motorcycles, sedans, and vans are all kinds of vehicles. Each of the vehicle types is a subclass of the Vehicle class. Similarly, the Vehicle class is the superclass of each specific vehicle type. Each subclass inherits attributes and methods from its superclass (in addition to having its own attributes and methods).

Inheritance provides several application benefits, including the following:

  • Using subclasses to provide specialized behaviors from the basis of common elements provided by the superclass. By using inheritance, you can reuse the code in the superclass many times.

  • Implementing abstract superclasses that define generic behaviors. This abstract superclass may define and partially implement behavior, while allowing you to complete the details with specialized subclasses.

Refer to Section 119.20, "Configuring Inheritance for a Child (Branch or Leaf) Class Descriptor" and Section 119.23, "Configuring Inherited Attribute Mapping in a Subclass" for detailed information on using inheritance with TopLink.

2.8.7 Concurrency

To have concurrent clients logged in at the same time, the server must spawn a dedicated thread of execution for each client. Java EE application servers do this automatically. Dedicated threads enable each client to work without having to wait for the completion of other clients. TopLink ensures that these threads do not interfere with each other when they make changes to the identity map or perform database transactions. Using the TopLink UnitOfWork class, your client can make transactional changes in an isolated and thread safe manner. The unit of work manages clones for the objects you modify to isolate each client's work from other concurrent clients and threads. The unit of work is essentially an object-level transaction mechanism that maintains all of the ACID (Atomicity, Consistency, Isolation, Durability) transaction principles as a database transaction. For more information on the unit of work, see Chapter 113, "Introduction to TopLink Transactions".

TopLink supports configurable optimistic and pessimistic locking strategies to let you customize the type of locking that the TopLink concurrency manager uses. For more information, see Section 16.4, "Descriptors and Locking".

2.8.8 Caching

TopLink caching improves application performance by automatically storing data returned as objects from the database for future use. This caching provides several advantages:

  • Reusing Java objects that have been previously read from the database minimizes database access

  • Minimizing SQL calls to the database when objects already exist in the cache

  • Minimizing network access to the database

  • Setting caching policies a class-by-class and bean-by-bean basis

  • Basing caching options and behavior on Java garbage collection

TopLink supports several caching polices to provide extensive flexibility. You can fine-tune the cache for maximum performance, based on individual application performance. Refer to Part L, "Cache" for complete information.

2.8.9 Nonintrusive Persistence

The TopLink nonintrusive approach of achieving persistence through a metadata architecture (see Section 2.9, "Working with TopLink Metadata") means that there are almost no object model intrusions.

To persist Java objects, TopLink does not require any of the following:

  • Persistent superclass or implementation of persistent interfaces

  • Store, delete, or load methods required in the object model

  • Special persistence methods

  • Generating source code into or wrapping the object model

When using entity beans with container-managed persistence, TopLink does not require any additional intrusion to the object model, other than the CMP specification requirements.

See Section 2.4, "Building and Using the Persistence Layer" for additional information on this nonintrusive approach.

2.8.10 Indirection

An indirection object takes the place of an application object so the application object is not read from the database until it is needed. Using indirection, or lazy loading in JPA, allows TopLink to create stand-ins for related objects. This results in significant performance improvements, especially when the application requires the contents of only the retrieved object rather than all related objects.

Without indirection, each time the application retrieves a persistent object, it also retrieves all the objects referenced by that object. This may result in lower performance for some applications.

Note:

Oracle strongly recommends that you use indirection in all situations.

TopLink provides several indirection models, such as proxy indirection, transparent indirection, and value holder indirection. TopLink also provides indirection support for EJB (see Section 17.2.4.6, "Indirection and EJB 2.n CMP").

See Section 17.2.4, "Indirection (Lazy Loading)" for more information.

2.8.11 Mutability

Mutability is a property of a complex field that specifies whether or not the field value may be changed or not changed as opposed to replaced.

An immutable mapping is one in which the mapped object value cannot change unless the object ID of the object changes: that is, unless the object value is replaced by another object value altogether.

A mutable mapping is one in which the mapped object value can change without changing the object ID of the object.

By default, TopLink assumes the following:

  • all TransformationMapping instances are mutable;

  • all JPA @Basic mapping types, except Serializable types, are immutable (including Date and Calendar types);

  • all JPA @Basic mapping Serializable types are mutable.

Whether a value is immutable or mutable largely depends on how your application uses your persistent classes. For example, by default, TopLink assumes that a persistent field of type Date is immutable: this means that as long as the value of the field has the same object ID, TopLink assumes that the value has not changed. If your application uses the set methods of the Date class, you can change the state of the Date object value without changing its object ID. This prevents TopLink from detecting the change. To avoid this, you can configure a mapping as mutable: this tells TopLink to examine the state of the persistent value, not just its object ID.

You can configure the mutability of the following:

  • TransformationMapping instances;

  • any JPA @Basic mapping type (including Date and Calendar types) individually;

  • all Date and Calendar types.

Mutability can affect change tracking performance. For example, if a transformation mapping maps a mutable value, TopLink must clone and compare the value in a unit of work (see Section 119.29, "Configuring Copy Policy"). If the mapping maps a simple immutable value, you can improve unit of work performance by configuring mapping as immutable.

Mutability also affects weaving. TopLink can only weave an attribute change tracking policy for immutable mappings.

For more information, see the following:

2.9 Working with TopLink Metadata

The TopLink metadata is the bridge between the development of an application and its deployed run-time environment. Capture the metadata using the following:

  • JPA annotations, persistence.xml, orm.xml, and EclipseLink JPA annotation and persistence.xml property extensions: the EclipseLink JPA persistence provider interprets all these sources of metadata to create an in-memory session and project at run time.

  • Oracle JDeveloper TopLink Editor or TopLink Workbench (see Section 2.9.2, "Creating Project Metadata" and Section 2.9.3, "Creating Session Metadata") to create TopLink sessions.xml and project.xml files which you pass to the TopLink run-time environment.

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

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

Using EclipseLink JPA, you also have the option of specifying your metadata using sessions.xml and project.xml while accessing your persistent classes using JPA and an EntityManager. For more information, see "What You May Need to Know About EclipseLink JPA Overriding Mechanisms" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#What_You_May_Need_to_Know_About_EclipseLink_JPA_Overriding_Mechanisms

Figure 2-2 TopLink Metadata

Description of Figure 2-2 follows
Description of "Figure 2-2 TopLink Metadata"

This section describes the following:

2.9.1 Advantages of the TopLink Metadata Architecture

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

  • Stores mapping information in XML descriptors–not in the domain model objects

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

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

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

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

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

Using EclipseLink JPA, you have the flexibility of expressing persistence metadata using standard JPA annotations, deployment XML, or both and you can optionally take advantage of EclipseLink JPA annotation and persistence.xml property extensions.

2.9.2 Creating Project Metadata

A TopLink project contains the mapping metadata that the TopLink runtime uses to map objects to a data source. The project is the primary object used by the TopLink runtime.

This section describes the principal contents of project metadata, including the following:

Using EclipseLink JPA, the TopLink runtime constructs an in-memory project based on any combination of JPA annotations, persistence.xml, orm.xml, and EclipseLink JPA annotation and persistence.xml property extensions. The use of a project.xml file is optional (see "What You May Need to Know About EclipseLink JPA Overriding Mechanisms" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#What_You_May_Need_to_Know_About_EclipseLink_JPA_Overriding_Mechanisms).

For more information about creating project.xml metadata, see Section 9.1.1, "project.xml File".

2.9.2.1 Descriptors and Mappings

TopLink maps persistent entities to the database in the application, using the descriptors and mappings you build with Oracle JDeveloper TopLink Editor or TopLink Workbench. These tools support several approaches to project development, including the following:

  • 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

TopLink Workbench supports all these options. The most common solution is to develop the persistent entities using a development tool, such as an integrated development environment (IDE) like Oracle Oracle JDeveloper, or a modeling tool, and to develop the relational model through appropriate relational design tools. You then use Oracle JDeveloper TopLink Editor or TopLink Workbench to construct mappings that relate these two models.

Although Oracle JDeveloper TopLink Editor and TopLink Workbench do offer 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.

For more information, see Chapter 16, "Introduction to Descriptors" and Chapter 17, "Introduction to Mappings".

2.9.2.1.1 Amending Descriptors

An amendment method lets you implement a TopLink feature that is not currently supported by Oracle JDeveloper TopLink Editor or TopLink Workbench. Simply write a Java method to amend the descriptor after it is loaded, and specify the method in Oracle JDeveloper TopLink Editor or TopLink Workbench for inclusion in the project metadata. See Section 119.35, "Configuring Amendment Methods" for detailed information on implementing an amendment method for a TopLink descriptor.

2.9.2.2 Data Source Login Information

For POJO projects, you configure a session login in the session metadata that specifies the information required to access the data source (see Section 2.9.3, "Creating Session Metadata").

For CMP projects, the project contains a deployment login that specifies the information required to access the data source.

For more information, see Section 15.2.4, "Projects and Login".

2.9.3 Creating Session Metadata

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 (see Section 9.1.2.2, "POJO Applications and Session Metadata"). In a CMP project, your application indirectly accesses a session acquired internally by the TopLink runtime (see Section 9.1.2.4, "CMP Applications and Session Metadata").

Using EclipseLink JPA, the TopLink runtime constructs an in-memory session based on any combination of JPA annotations, persistence.xml, orm.xml, and EclipseLink JPA annotation and persistence.xml property extensions. The use of a sessions.xml file is optional (see "What You May Need to Know About EclipseLink JPA Overriding Mechanisms" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#What_You_May_Need_to_Know_About_EclipseLink_JPA_Overriding_Mechanisms).

2.9.4 Deploying Metadata

The project.xml and sessions.xml file are packaged for deployment differently according to the type of application you are deploying.

For more information, see the following:

Using EclipseLink JPA, you also have the option of specifying your metadata using sessions.xml and project.xml while accessing your persistent classes using JPA and an EntityManager. For more information, see "What You May Need to Know About EclipseLink JPA Overriding Mechanisms" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#What_You_May_Need_to_Know_About_EclipseLink_JPA_Overriding_Mechanisms.

2.10 Using Weaving

Weaving is a technique of manipulating the byte-code of compiled Java classes. Weaving is used to enhance both JPA entities and Plain Old Java Object (POJO) classes for such things as lazy loading, change tracking, fetch groups, and internal optimizations.

This section describes the following:

2.10.1 Configuring Dynamic Weaving Using EclipseLink Agent

When using EclipseLink JPA outside of an EJB 3.0 container, consider dynamic weaving. For more information, see "How to Configure Dynamic Weaving for JPA Entities Using EclipseLink Agent" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#How_to_Configure_Dynamic_Weaving_for_JPA_Entities_Using_the_EclipseLink_Agent

2.10.1.1 To Configure Dynamic Weaving Using EclipseLink Agent

For information, see the following:

2.10.2 Configuring Static Weaving

Consider this option to weave all applicable class files at build time so that you can deliver prewoven class files. For more information, see "How to Configure Static Weaving for JPA Entities" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#How_to_Configure_Static_Weaving_for_JPA_Entities.

Note that for weaving, you use a persistence.xml file in both JPA and POJO applications.

For information on packaging and deployment of POJO applications, see Section 2.10.4, "Packaging a POJO Application for Weaving".

2.10.3 Disabling Weaving Using TopLink Persistence Unit Properties

To disable weaving, you use persistence unit properties in both JPA and POJO applications. For more information, see "How to Disable Weaving Using EclipseLink Persistence Unit Properties" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#How_to_Disable_Weaving_Using_EclipseLink_Persistence_Unit_Properties.

For information on packaging and deployment of POJO application, see Section 2.10.4, "Packaging a POJO Application for Weaving".

2.10.4 Packaging a POJO Application for Weaving

To package a POJO application for weaving, you create a JAR that contains a sessions.xml file and a persistence.xml file.

2.10.4.1 To Package a POJO Application for Weaving

  1. Create a sessions.xml file for your application.

    For more information, Chapter 87, "Introduction to TopLink Sessions".

  2. Create a persistence.xml file for your application and reference your sessions.xml file, as Example 2-1 shows.

    Example 2-1 persistence.xml File for a EclipseLink JPA Application

    <persistence>
        <persistence-unit name="appname">
            <exclude-unlisted-classes>false</exclude-unlisted-classes>
            <properties>
                <property
                    name="eclipselilnk.session-name"
                    value="appname-session"
                >
                <property
                    name="eclipselink.sessions-xml"
                    value="sessions.xml"
                >
            </properties>
        </persistence-unit>
    </persistence>
    
  3. Create a JAR file that contains your POJO classes, sessions.xml file, and persistence.xml file, as Example 2-2 shows.

    Put both the persistence.xml and sessions.xml file in a META-INF directory.

    Example 2-2 JAR File for a POJO Application

    appname.jar
        META-INF
            persistence.xml
            sessions.xml
        *.java
    
  4. Weave the JAR.

    For more information, see the following:

2.10.5 What You May Need to Know About Weaving and POJO Classes

TopLink uses weaving to enable the following for POJO classes:

TopLink weaves all the POJO classes in the JAR you create when you package a POJO application for weaving. For more information, see Section 2.10.4, "Packaging a POJO Application for Weaving".

TopLink weaves all the classes defined in the persistence.xml file. That is the following:

  • all the classes you list in the persistence.xml file;

  • all classes relative to the JAR containing the persistence.xml file if element <exclude-unlisted-classes> is false.

2.10.6 What You May Need to Know About Weaving and Java EE Application Servers

The default TopLink weaving behavior applies in any Java EE JPA-compliant application server using the EclipseLink JPA persistence provider.To change this behavior, modify your persistence.xml (for your JPA entities or POJO classes) to use EclipseLink JPA properties, EclipseLink JPA annotations, or both.

For lazy loading (indirection) differences between Java EE and Java SE applications, see "EclipseLink JPA Support for Lazy Loading by Mapping Type" table of EclipseLink Developer's Guide at http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#Table_19-33

2.11 Considering Three-Tier Architecture

The three-tier Web application architecture generally includes the connection of a server-side Java application to the database through a JDBC connection (see Figure 2-3). In this pattern, TopLink resides within a Java server (a Java EE server or a custom server), with several possible server integration points. The application can support Web clients such as servlets, Java clients, and generic clients using XML or Common Object Request Broker Architecture (CORBA).

The three-tier application is a common architecture in which TopLink resides within a Java server (either a Java EE server or a custom server). In this architecture, the server session provides clients with shared access to JDBC connections and a shared object cache. Because it resides on a single JVM, this architecture is simple and easily scalable. The TopLink persistent entities in this architecture are generally Java objects.

This architecture often supports Web-based applications in which the client application is a Web client, a Java client, or a server component.

Figure 2-3 Three Tier Architecture

Description of Figure 2-3 follows
Description of "Figure 2-3 Three Tier Architecture"

Although not all three-tier applications are Web-based, this architecture is ideally suited to distributed Web applications. In addition, although it is also common to use EJB in a Web application, this TopLink architecture does not.

2.11.1 Example Implementations

Examples of three-tier architecture implementation include the following:

  • A Model-View-Controller Model 2 architectural design pattern that runs in a Java EE container with servlets and JSP that uses TopLink to access data without EJB.

  • A Swing or Abstract Window Toolkit (AWT) client that connects to a server-side Java application through RMI, without an application server or container.

2.11.2 Advantages and Disadvantages

The three-tier Web application architecture offers the following advantages:

  • High performance, lightweight persistent objects

  • High degree of flexibility in deployment platform and configuration

The disadvantage of this architecture is it is less standard than EJB.

2.11.3 Variation Using Remote Sessions

TopLink includes a session type called remote session. The session offers the full session API and contains a cache of its own, but exists on the client system rather than on the TopLink server. Communications can be configured to use RMI or RMI-Internet Inter-Object Request Broker Protocol (IIOP).

Remote session operations require a corresponding client session on the server.

Although this is an excellent option for you if you wish to simplify the access from the client tier to the server tier, it is less scalable than using a client session and does not easily allow changes to server-side behavior.

For more information, see Section 87.9, "Remote Sessions".

2.11.4 Technical Challenges

The three-tier application with a stateless client presents several technical challenges, including the following:

  • Transaction management in a stateless environment

    A common design practice is to delimit client requests within a single unit of work (transactional session). In a stateless environment, this may affect how you design the presentation layer. For example, if a client requires multiple pages to collect information for a transaction, then the presentation layer must retain the information from page to page until the application accumulates the full set of changes or requests. At that point, the presentation layer invokes the unit of work to modify the database.

  • Optimistic locking in a stateless environment

    In a stateless environment, take care to avoid processing out-of-date (stale) data. A common strategy for avoiding stale data is to implement optimistic locking, and store the optimistic lock values in the object.

    This solution requires careful implementation if the stateless application serializes the objects, or sends the contents of the object to the client in an alternative format. In this case, transport the optimistic lock values to the client in the HTTP contents of an edit page. You must then use the returned values in any write transaction to ensure that the data did not change while the client was performing its work.

    For more information about locking, see Section 119.26, "Configuring Locking Policy".

  • External JDBC pools

    By default, TopLink manages its own connection pools. You can also configure TopLink to use connection pooling offered by the host application server. This feature is useful for shared connection pools and is required for JTA/JTS integration (see Section 97.4, "Configuring External Connection Pooling").

  • JTA/JTS Integration

    JTA and JTS are standard Java components that enable sessions to participate in distributed transactions. You must configure TopLink to use JTA/JTS to use session beans in the architecture (see Section 115.13, "Integrating the Unit of Work with an External Transaction Service").

  • Cache coordination

    If you choose to use multiple servers to scale your application, you may require TopLink cache coordination (see Chapter 102, "Introduction to Cache").

2.12 Considering Two-Tier Architecture

A two-tier application generally includes a Java client that connects directly to the database through TopLink. The two-tier architecture is most common in complex user interfaces with limited deployment. The database session provides TopLink support for two-tier applications.

For more information, see Chapter 87, "Introduction to TopLink Sessions".

Figure 2-4 Two-Tier Architecture

Description of Figure 2-4 follows
Description of "Figure 2-4 Two-Tier Architecture"

Although the two-tier architecture is the simplest TopLink application pattern, it is also the most restrictive, because each client application requires its own session. As a result, two-tier applications do not scale as easily as other architectures.

Two-tier applications are often implemented as user interfaces that directly access the database (see Figure 2-4). They can also be non-interface processing engines. In either case, the twoEtier model is not as common as the three-tier model.

The following are key elements of an efficient twoEtier (client-server) architecture with TopLink:

  • Minimal dedicated connections from the client to the database

  • An isolated object cache

2.12.1 Example Implementations

An example of a two-tier architecture implementation is a Java user interface (Swing/AWT) and batch data processing.

2.12.2 Advantages and Disadvantages

The advantage of the twoEtier design is its simplicity. The TopLink database session that builds the two-tier architecture provides all the TopLink features in a single session type, thereby making the two-tier architecture simple to build and use.

The most important limitation of the two-tier architecture is that it is not scalable, because each client requires its own database session.

2.12.3 Technical Challenges

The current trend toward multitiered Web applications makes the two-tier architecture less common in production systems, but no less viable. Because there is no shared cache in a two-tier system, you risk encountering stale data if you run multiple instances of the application. This risk increases as the number of individual database sessions increases.

To minimize this problem, TopLink offers support for several data locking strategies. These include pessimistic locking and several variations of optimistic locking. For more information, see Section 119.26, "Configuring Locking Policy".

2.13 Considering EJB Session Bean Facade Architecture

This architecture is an extension of the threeEtier pattern, with the addition of EJB session beans wrapping the access to the application tier. Session beans provide public API access to application operations, enabling you to separate the presentation tier from the application tier. The architecture also lets you use session beans within a Java EE container.This type of architecture generally includes JTA integration, and serialization of data to the client.

Figure 2-5 Three-Tier Architecture Using Session Beans and Java Objects

Description of Figure 2-5 follows
Description of "Figure 2-5 Three-Tier Architecture Using Session Beans and Java Objects"

A common extension to the three-tier architecture is to combine session beans and persistent Java objects managed by TopLink. The resulting application includes session beans and Java objects on a TopLink three-tier architecture (see Figure 2-5).

The three-tier architecture creates a server session and shares it between the session beans in the application. When a session bean needs to access a TopLink session, the bean obtains a client session from the shared server session. This architecture has the following key features:

  • Session beans delimit transactions.

    Configure TopLink to work with a JTA system and its associated connection pool.

  • Accessing the persistent objects on the client side causes them to be serialized.

    Ensure that when the objects re-emerge on the server-side, they properly merge into the cache to maintain identity.

2.13.1 Example Implementation

An example of the EJB session bean facade architecture implementation is a Model-View-Controller Model 2 architectural design pattern that runs in a Java EE container with servlets and JSP and uses the session bean enabled by TopLink to access data without EJB.

2.13.2 Advantages and Disadvantages

The EJB session bean facade architecture is a popular and effective compromise between the performance of persistent Java objects, and the benefits of EJB for standardized client development and server scalability. It offers the following advantages:

  • Less overhead than an EJB CMP application

    TopLink shares access to the project, descriptor, and login information across the beans in the application.

  • Future compatibility with other servers

    This design isolates login and EJB server-specific information from the beans, which lets you migrate the application from one application server to another without major recoding or rebuilding.

  • Shared read cache

    This design offers increased efficiency by providing a shared cache for reading objects.

The key disadvantage of this model is the need to transport the persistent model to the client. If the model involves complex object graphs in conjunction with indirection (lazy loading), this can present many challenges with inheritance, indirection, and relationships.

For more information about managing inheritance, indirection and relationships, see Part VIII, "Mappings".

2.13.3 What Are Session Beans

Session beans model a process, operation, or service and as such, are not persistent entities. However, session beans can use persistence mechanisms to perform the services they model.

Under the session bean model, a client application invokes methods on a session bean that, in turn, performs operations on Java objects enabled by TopLink. Session beans execute all operations related to TopLink on behalf of the client.

The EJB specifications describe session beans as either stateless or stateful.

Stateful beans maintain a conversational state with a client; that is, they retain information between method calls issued by a particular client. This enables the client to use multiple method calls to manipulate persistent objects.

Stateless beans do not retain data between method calls. When the client interacts with stateless session beans, it must complete any object manipulations within a single method call.

2.13.4 Technical Challenges

Your application can use both stateful and stateless session beans with a TopLink client session or database session. When you use session beans with a TopLink session, the type of bean used affects how it interacts with the session.

  • Stateless session beans and the TopLink session

    Stateless beans store no information between method calls from the client. As a result, reestablish the connection of the bean to the session for each client method call. Each method call through TopLink obtains a client session, makes the appropriate calls, and releases the reference to the client session.

  • Stateful session beans and the TopLink session

    Your EJB server configuration includes settings that affect the way it manages beans–settings designed to increase performance, limit memory footprint, or set a maximum number of beans. When you use stateful beans, the server may deactivate a stateful session bean enabled by TopLink out of the JVM memory space between calls to satisfy one of these settings. The server then reactivates the bean when required, and brings it back into memory.

    This behavior is important, because a TopLink session instance does not survive passivation. To maintain the session between method calls, release the session during the passivation process and re-obtain it when you reactivate the bean.

  • External JDBC pools

    By default, TopLink manages its own connection pools. For the session bean architecture, you must configure TopLink to use connection pooling offered by the host application server. This feature is useful for shared connection pools and is required for JTA/JTS integration (see Section 97.4, "Configuring External Connection Pooling").

  • JTA/JTS integration

    JTA and JTS are standard Java components that enable sessions to participate in distributed transactions. You must configure TopLink to use JTA/JTS to use session beans in the architecture (see Section 115.13, "Integrating the Unit of Work with an External Transaction Service").

  • Cache coordination

    If you choose to use multiple servers to scale your application, you may require TopLink cache coordination (see Section 102.3, "Cache Coordination").

2.13.5 What Is a Unit of Work Merge

You can use a unit of work to enable your client application to modify objects on the database. The unit of work merge functions employ mappings to copy the values from the serialized object into the unit of work, and to calculate changes.

For more information, see Section 115.5, "Merging Changes in Working Copy Clones".

2.14 Considering EJB Entity Beans with CMP Architecture

CMP is the part of the Java EE component model that provides an object persistence service that an EJB container uses to persist entity beans. CMP provides distributed, transactional, secure access to persistent data, with a guaranteed portable interface.

This architecture is an extension of the threeEtier architecture, in which the implementation of persistence methods is handled by the container at runtime. As a bean provider, you only need to specify in a deployment descriptor those persistent fields and relationships for which the container must handle data access and, optionally, an abstract representation of the database schema.

TopLink CMP is an extension of the TopLink persistence framework that provides custom integration to EJB containers of various application servers (see Section 8.1, "Introduction to the Application Server Support"). For more information about choosing an application server, see Section 2.2.2, "Target Platforms". TopLink integrates with the EJB container in this architecture to augment the container's persistence manager.

TopLink CMP integration is nonintrusive (see Figure 2-6). Through a combination of run-time integration and code generation, the container uses TopLink internally and the bean user interacts with entity beans with container-managed persistence according to their standard API. This lets you combine the standard interfaces and power of CMP and a container with TopLink flexibility, performance, and productivity.

Figure 2-6 Three-Tier CMP Architecture

Description of Figure 2-6 follows
Description of "Figure 2-6 Three-Tier CMP Architecture"

For more information, see the following:

2.14.1 Example Implementation

An example of the entity beans with container-managed persistence implementation is a Model-View-Controller Model 2 architectural design pattern that runs in a Java EE container, with servlets and JSP that access either session beans or entity beans with container-managed persistence enhanced by TopLink.

2.14.2 Advantages and Disadvantages

A three-tier architecture using entity beans with container-managed persistence offers the following advantages:

  • It allows for entity beans with container-managed persistence supplied with sophisticated TopLink features such as caching and mapping support, storing bean data across more than one table, composite primary keys, and data conversion.

  • It presents a standard method to access data, which lets you create standardized, reusable business objects.

  • It is well-suited to create coarse-grained objects, which TopLink relates to dependent, lightweight, regular Java objects (TopLink can also manage container-managed relationships to lightweight dependent Java objects).

  • TopLink provides for lazy initialization of referenced objects and beans (see Section 17.2.4, "Indirection (Lazy Loading)").

  • TopLink provides functionality for transactional copies of beans, allowing concurrent access by several clients, rather than relying on individual serialization.

  • TopLink provides advanced query capabilities, as well as dynamic querying, including the ability to define queries at the bean-level rather than the data source level and to use a rich set of querying and finder options.

  • TopLink maintains bean and object identity.

The disadvantage of this architecture is that pure entity bean with container-managed persistence architectures can impose a high overhead cost. This is especially true when a data model has a large number of fine-grained classes with complex relationships.

2.14.3 Technical Challenges

The key technical challenge in this architecture lies in integrating components into a cohesive system. For example, this architecture requires a specific TopLink integration with the application server or Java EE container.

Other issues include the following:

2.14.3.1 External JDBC Pools

By default, TopLink manages its own connection pools. You can also configure TopLink to use connection pooling offered by the host application server. This feature is useful for shared connection pools and is required for JTA/JTS integration (see Section 97.4, "Configuring External Connection Pooling").

2.14.3.2 JTA/JTS Integration

JTA and JTS are standard Java components that enable sessions to participate in distributed transactions. You must configure TopLink to use JTA/JTS to use session beans in the architecture (see Section 115.13, "Integrating the Unit of Work with an External Transaction Service").

2.14.3.3 Cache Coordination

If you choose to use multiple servers to scale your application, you may require TopLink cache coordination (see Section 102.3, "Cache Coordination").

2.14.3.4 Maintaining Bidirectional Relationships

When one-to-one or many-to-many relationship is bidirectional, you must maintain the back pointers as the relationships change.

TopLink automatically maintains the relationship between two entity beans.

To set the back pointer manually, do one of the following:

  • Code the entity bean to maintain the back pointer when the relationship is established or modified (recommended).

  • Code the client to explicitly set the back pointer.

If you code the entity bean to set back pointers, the client is freed of this responsibility. This has the advantage of encapsulating this maintenance implementation in the bean.

In a one-to-many relationship, a source bean might have several dependent target objects. For example, an EmployeeBean might own several dependent PhoneNumber instances. When you add a new dependent object (a PhoneNumber, in this example) to an employee, you must set the PhoneNumber instance's back pointer to its owner (the employee). Maintaining a one-to-many relationship in the entity bean involves getting the local object reference from the context of the EmployeeBean, and then updating the back pointer, as Example 2-3 shows.

Example 2-3 Setting the Back-Pointer in the Entity Bean

// obtain owner and phoneNumber
owner = empHome.findByPrimaryKey(ownerId); 
phoneNumber = new PhoneNumber("cell", "613", "5551212");
// add phoneNumber to the phoneNumbers of the owner
owner.addPhoneNumber(phoneNumber);

// Maintain the relationship in the Employee's addPhoneNumber method 
public void addPhoneNumber(PhoneNumber newPhoneNumber) {
    // get, then set the back pointer to the owner
    Employee owner = (Employee)this.getEntityContext().getEJBLocalObject();
    newPhoneNumber.setOwner(owner); 
    // add new phone
    getPhoneNumbers().add(newPhoneNumber);
}

For more information, see the following:

2.14.3.5 Managing Dependent Objects

Unlike EJB, TopLink dependent persistent objects can be sent back and forth between a client and a server. When objects are serialized, the risk exists the objects can cause the cache to lose the identity of the objects or attempt to cache duplicate identical objects. To avoid potential problems, use the bean setter methods when adding dependent objects to relationship collections, as Example 2-4 shows. This enables TopLink to handle merging of objects in the cache.

Example 2-4 Managing Dependent Objects

addPhoneNumber(PhoneNumber phone) { 
    Collection phones = this.getPhoneNumbers(); 
    Vector newCollection = new Vector();
    newCollection.addAll(phones); 
    newCollection.add(phone); 
    this.setPhones(newCollection); 
}

2.14.3.6 Managing Collections of EJBObject Objects

Collections generally use the equals method to compare objects. This is not a problem in the case of an object that contains a collection of EJBObject objects, because the EJB container collection handles equality appropriately.

2.15 Considering EJB Entity Beans with BMP Architecture

BMP is the part of the Java EE component model that lets you, the bean provider, implement the entity bean's persistence directly in the entity bean class or in one or more helper classes that you provide.

This architecture is an extension of the three-tier architecture, in which the persistent data is bean managed within an entity bean using code that you implement. The client code accesses the data through the entity bean interface.

TopLink BMP is an extension of the TopLink persistence framework that provides base class BMPEntityBase as a starting point for your BMP development. This class provides an implementation for all methods (except ejbPassivate) required by the EJB specifications prior to 3.0. Subclass BMPEntityBase to create a TopLink-enabled entity bean with bean-managed persistence.To use the BMPEntityBase class, perform the following:

  1. Create a TopLink session (see Chapter 87, "Introduction to TopLink Sessions") for your application.

  2. Add a BMPWrapperPolicy to each descriptor that represents an entity bean with bean-managed persistence.

    The BMPWrapperPolicy provides TopLink with the information to create remote objects for entity beans and to extract the data out of a remote object.

  3. Create the home and remote interfaces.

  4. Create deployment descriptors (see Chapter 8, "Integrating TopLink with an Application Server" and Chapter 9, "Creating TopLink Files for Deployment").

  5. Package your application (see Chapter 10, "Packaging a TopLink Application").

  6. Deploy the beans (see Chapter 11, "Deploying a TopLink Application").

To make full use of TopLink session and unit of work features, TopLink provides a hook into its functionality through the BMPDataStore class. Use this class to translate EJB-required functionality into simple calls.

The BMPDataStore class provides implementations of LOAD and STORE, multiple finders, and REMOVE functionality. The BMPDataStore class requires a TopLink session. A single instance of BMPDataStore must exist for each bean type deployed within a session. When creating a BMPDataStore, pass in the session name of the session that the BMPDataStore must use to persist the beans and the class of the bean type being persisted. Store the BMPDataStore in a global location so that each instance of a bean type uses the correct store method.

TopLink BMP support (see Figure 2-7) lets you combine the standard interfaces of entity beans with bean-managed persistence with TopLink flexibility, performance, and productivity.

Figure 2-7 Three-Tier BMP Architecture

Description of Figure 2-7 follows
Description of "Figure 2-7 Three-Tier BMP Architecture"

TopLink supports BMP. To use BMP support, the home interface must inherit from the oracle.toplink.ejb.EJB20Home. To make calls to the BMPEntityBase, the findAll method must call the EJB 2.0 version of the methods. These methods are prefixed with ejb20. For example, in the EJB 2.0 version, the findAll method appears as ejb20FindAll.

To use local beans, use the oracle.toplink.ejb.EJB20LocalHome setting instead of the default oracle.toplink.ejb.EJB20Home. Instead of the oracle.toplink.ejb.BMPWrapperPolicy setting, use the oracle.toplink.ejb.bmp.BMPLocalWrapperPolicy setting.

To accommodate both local and remote configurations, ensure the following:

  • For a bean that has a single interface, use the corresponding wrapper policy (local or remote) for the descriptor.

  • Beans can only participate in relationships as either local or remote interfaces, not both.

For more information, see the following:

2.15.1 Example Implementations

An example of the entity beans with bean-managed persistence implementation is a Model-View-Controller Model 2 architectural design pattern that runs in a Java EE container, with servlets and JSP that access session beans and entity beans with bean-managed persistence enhanced by TopLink.

2.15.2 Advantages and Disadvantages

Using BMP with a TopLink three-tier architecture offers the following advantages:

  • It simplifies the BMP method calls. These can be inherited from an abstract bean class, rather than being generated.

  • TopLink makes BMP easier to implement.

  • It enables you to implement database-independent code in the bean methods.

  • The architecture supports features such as complex relationships, caching, object-level and dynamic queries, and the unit of work.

The main disadvantages of BMP include the following:

  • You must create the persistence mechanisms in the bean code.

  • It is not as transparent or efficient as CMP.

  • TopLink-only Java object applications offer the same degree of independence from the application server.

2.15.3 Technical Challenges

The key technical challenge in this architecture lies in integrating components into a cohesive system. For example, this architecture requires a specific TopLink integration with the application server or Java EE container.

Other issues include the following:

2.15.3.1 External JDBC Pools

By default, TopLink manages its own connection pools. You can also configure TopLink to use connection pooling offered by the host application server. This feature is useful for shared connection pools and is required for JTA/JTS integration (see Section 97.4, "Configuring External Connection Pooling").

2.15.3.2 JTA/JTS Integration

JTA and JTS are standard Java components that enable sessions to participate in distributed transactions. You must configure TopLink to use JTA/JTS to use session beans in the architecture (see Section 115.13, "Integrating the Unit of Work with an External Transaction Service").

2.15.3.3 Cache Coordination

If you choose to use multiple servers to scale your application, you may require TopLink cache coordination (see Section 102.3, "Cache Coordination").

2.16 Considering JPA Entity Architecture

A part of the EJB 3.0 specification, the Java Persistence API (JPA) is a lightweight, POJO-based framework for Java persistence. JPA focuses on object relational mapping and contains a full object relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. Object relational mapping with the JPA is completely metadata-driven. JPA supports a SQL-like query language for both static and dynamic queries. It also supports the use of pluggable persistence providers.

JPA includes the following concepts:

  • Entity–any application-defined object with the following characteristics can be an entity:

    • it can be made persistent;

    • it has a persistent identity (a key that uniquely identifies an entity instance and distinguishes it from other instances of the same entity type. An entity has a persistent identity when there is a representation of it in a data store);

    • it is partially transactional in a sense that a persistence view of an entity is transactional (an entity is created, updated and deleted within a transaction, and a transaction is required for the changes to be committed in the database). However, in-memory entities can be changed without the changes being persisted.

    • it is not a primitive, a primitive wrapper, or built-in object. An entity is a fine-graned object that has a set of aggregated state that is typically stored in a single place (such as a row in a table), and have relationships to other entities.

  • Entity metadata–describes every entity. Metadata could be expressed as annotations (specifically defined types that may be attached to or place in front of Java programming elements) or XML (descriptors).

  • Entity manager–enables API calls to perform operations on an entity. Until an entity manager is used to create, read, or write an entity, the entity is just a regular nonpersistent Java object. When an entity manager obtains a reference to an entity, that entity becomes managed by the entity manager. The set of managed entity instances within an entity manager at any given time is called its persistence context–only one Java instance with the same persistent identity may exist in a persistence context at any time.

    You can configure an entity manager to be able to persist or manage certain types of objects, read or write to a particular database, and be implemented by a specific persistence provider. The persistence provider supplies the backing implementation engine for JPA, including the EntityManager interface implementation, the Query implementation, and the SQL generation.

    Entity managers are provided by an EntityManagerFactory. The configuration for an entity manager is bound to the EntityManagerFactory, but it is defined separately as a persistence unit. You name persistence units to allow differentiation between EntityManagerFactory objects. This way your application obtains control over which configuration to use for operations on a specific entity. The configuration that describes the persistence unit is defined in a persistence.xml file.

    The following description expresses relationships between JPA concepts:

    • Persistence creates one or more EntityManagerFactory objects;

    • each EntityManagerFactory is configured by one persistence unit;

    • EntityManagerFactory creates one or more EntityManager objects;

    • one or more EntityManager manages one PersistenceContext.

TopLink implementation of JPA is provided by EclipseLink.

For more information, see the following:

2.16.1 Example Implementations

An example of the entity beans with bean-managed persistence implementation is a Model-View-Controller Model 2 architectural design pattern that runs in a Java EE container, with servlets and JSP that access session beans and EJB 3.0-compliant entities using the EclipseLink JPA persistence provider.

2.16.2 Advantages and Disadvantages

The use of EclipseLink JPA entities offers the following advantages:

  • POJO persistence–in JPA, persistent objects are POJOs.

  • Object relational mapping is completely metadata-driven.

  • The persistence API exists as a separate layer from the persistent objects and does not intrude upon them.

  • Using the query framework you can query across entities and their relationships without having to use concrete foreign keys or database columns. Also, you can define queries statically in metadata or create them dynamically by passing query criteria on construction. Queries can return entities as results.

  • Entities are mobile: objects are able to move from one JVM to another and back, and at the same time be usable by the application.

  • You can configure persistence features through the use of Java SE 5 annotations, or XML, or a combination of both. You may also rely on defaults.

  • If your application is running inside a container, the container provides support and ease of use; you can configure the same application to run outside a container.

2.17 Considering Web Services Architecture

A Web services architecture is similar to the three-tier (see Section 2.11, "Considering Three-Tier Architecture") or session bean (see Section 2.13, "Considering EJB Session Bean Facade Architecture") architecture, however, in a Web services architecture, you encapsulate business logic (the service) in a Web service instead of (or in addition to) using session beans. In a Web services architecture, clients communicate with your application using SOAP messages (XML over HTTP).

Figure 2-8 Web Services Architecture

Description of Figure 2-8 follows
Description of "Figure 2-8 Web Services Architecture"

As in any architecture, you can use TopLink to persist objects to relational or EIS data sources. However, in a Web services architecture, you can also use TopLink to map your object model to an XML schema for use with the Web service or as the Web service XML serializer.

2.17.1 Example Implementations

An example of a Web services architecture implementation is the use of a Web service to expose parts of an existing application to a remote client (typically another application) by way of SOAP messages. In this application, you can use TopLink XML to unmarshall XML messages to Java objects to facilitate requests and marshall Java object responses back into XML for transmission to the client.

2.17.2 Advantages and Disadvantages

Using TopLink in Web services architecture has many advantages, including, but not limited to, the following:

  • you can map XML messages to an existing Java object model;

  • you can achieve a high level of complexity of mapping support;

  • compliance with the JAXB standards;

  • providing a scalable, high-performing solution.

One debatable disadvantage is this solution's complexity over a simple RMI session bean service.

2.17.3 Technical Challenges

As with any technology, there are technical challenges associated with the use of TopLink in Web services architecture. These technical challenges are mostly related to special-case scenarios, such as when you need to implement a custom serializer because you have both the Java objects and the schema.

For more information, see the following:

2.18 Considering EclipseLink Service Data Objects (SDO) Architecture

An EclipseLink SDO architecture uses the SDO 2.1 framework for data application and development. For more information, see "Considering EclipseLink Service Data Objects (SDO) Architecture" section of EclipseLink Developer's Guide at http://wiki.eclipse.org/Introduction_to_EclipseLink_Application_Development_%28ELUG%29#Considering_EclipseLink_Service_Data_Objects_.28SDO.29_Architecture.