Oracle TopLink Object-XML

How-To Document

 

May 2006

After reading this How-To document, you will be able to:

Software Requirements

Conventions

The following conventions are used in this document:

Introduction

TopLink now includes object-to-XML support. This How-To document shows you how to use TopLink to map an existing object model to an existing XML Schema. The mapping metadata is then be created using the TopLink Workbench, and used in the TopLink runtime to unmarshall an XML document, manipulate the data, and then marshal the data back to XML.

Using TopLink's Object-to-XML Support

In this section of this How-To document, you will map the existing object model (CustomerModel.zip) to the existing XML Schema (Customer.xsd). You will then use the metadata created in the TopLink runtime to manipulate an XML document (Customer-data.xml).

Step 1: Folder Setup

Create the <DEMO_HOME> directory and place the Customer.xsd at the root of the directory.

Step 2: Compile the Customer Model

Extract the Java source files from CustomerModel.zip and compile them to the <DEMO_HOME>/classes folder.

Step 3: Create a New TopLink Workbench XML Project

  1. Start the TopLink Workbench executing the workbench.cmd (Windows) or the workbench.sh (UNIX) file located in the <ORACLE_HOME>/bin directory.

  2. From the File menu, select New > Project.

    The Create New TopLink Workbench Project dialog appears.

    Description of NewProjectDialog.gif follows
    Description of the illustration NewProjectDialog.gif

  3. Enter the following into the Create New TopLink Workbench Project dialog.

    Name: CustomerProject

    Data Source: XML

Step 4: Import the XML Schema into the TopLink Workbench

Before any mapping can be done, the XML Schema must be loaded into the TopLink Workbench. To do this, follow this procedure:

  1. Expand the CustomerProject project in the Navigator pane.

  2. Right-click the Schemas node and select Import Schema....

    The Import Schema dialog appears.

    Description of ImportSchema.gif follows
    Description of the illustration ImportSchema.gif

  3. Enter the following into the Import Schema dialog:

    • Name: Customer

      This name will uniquely identify this XML schema in the TopLink Workbench.

    • File: <DEMO_HOME>/Customer.xsd

  4. Click OK.

    The TopLink Workbench imports the schema.

Step 5: Import the Domain Classes into the TopLink Workbench

The next step is to load the customer model classes into the TopLink Workbench. All TopLink Workbench features related to Java classes are the same regardless of the type of data source chosen (Database, EIS, or XML). To load the customer model classes into the TopLink Workbench:

  1. Select the CustomerProject project in the Navigator pane.

  2. Click on the General tab in the Editor pane.

  3. To update the project classpath to include the Java classes you compiled in "Step 2: Compile the Customer Model", click Browse and navigate to the <DEMO_HOME>/classes folder.

  4. Select the folder and click OK.

  5. Right-click the CustomerProject project in the Navigator pane and select Add or Refresh Classes....

    The Select Classes dialog appears.

    Description of selectclasses.gif follows
    Description of the illustration selectclasses.gif

  6. With the examples.ox.model item selected in the Available Packages/Classes area, click the right-pointing arrow button. The examples.ox.model package is added to the Selected Classes area.

  7. Click OK.

    The TopLink Workbench imports the classes and creates descriptors for each.

    Description of ImportClasses.gif follows
    Description of the illustration ImportClasses.gif

Step 6: Set the Schema Context for Each Descriptor

Java objects are mapped to complex types (global or local) in TopLink. The objects' attributes and relationships are mapped relative to the schema context set on the descriptor. The TopLink Workbench presents a tree representing that portion of the XML schema starting with that complex type, so in this way you're never dealing with the entire schema.

Description of Descriptor.gif follows
Description of the illustration Descriptor.gif

To choose a schema context for a descriptor:

  1. Select the Customer descriptor in the Navigator pane.

  2. Click on Descriptor Info tab.

  3. Click the Browse... button opposite Schema Context in the Editor pane.

    The Choose Schema Context dialog appears.

    Description of ChooseSchemaContext.gif follows
    Description of the illustration ChooseSchemaContext.gif

  4. Select the customer element in the Choose Schema Context dialog.

  5. Click the OK button.

Step 7: Specify At Least One Root Object

If the object is to be passed directly to a marshal operation, it must be flagged in the TopLink Workbench as a Document Root and have a Default Root Element specified. To do this:

  1. Select the Customer descriptor in the Navigator pane.

  2. Click on Descriptor Info tab.

  3. Click on the Document Root checkbox in the Editor pane.

Description of RootObject.gif follows
Description of the illustration RootObject.gif

Step 8: Map a Simple Attribute

Simple object attributes are mapped to XML attributes or text nodes. This is done using the XML Direct Mapping for the single case, and XML Direct Collection Mapping for the collection case. In this step, we map the Address attribute province.

  1. Expand the Address descriptor in the Navigator pane.

  2. Right-click the province attribute and select Map as > Direct.

    Description of DirectMapping.gif follows
    Description of the illustration DirectMapping.gif

    Note that there is no direct relationship between the name of the Address object's province attribute and the name of the corresponding XML node state. This helps to decouple the object model from the XML document.

  3. To specify the XPath for this mapping, click the Browse... button in the Editor pane.

    The Choose XPath dialog appears.

    Description of DirectMappingXPath.gif follows
    Description of the illustration DirectMappingXPath.gif

    Although you have mapped an attribute of the object to a node in an XML document, the values may not correspond exactly. TopLink provides a number of converters (and the ability to create your own) to translate the values during marshalling and unmarshalling.

  4. To create an Object Type Converter to convert state abbreviations in the XML document to full state names in the object, select the Converter tab, and configure the Object Type Converter options as shown.

    Description of DirectMappingObjectType.gif follows
    Description of the illustration DirectMappingObjectType.gif

Step 9: Map a Simple Attribute Based on Position

Normally when an element is mapped more than once (maxOccurs !=1), it is mapped to a collection type in the object model. In some circumstances, it may be preferable to map a non-collection attribute to an item in the collection, based on its position. This concept can be used with XML Direct Mapping and XML Direct Collection Mapping. In this step, we map the Address attribute suite.

  1. Expand the Address descriptor in the Navigator pane.

  2. Right-click the suite attribute and select Map as > Direct.

    Description of DirectMappingSuite.gif follows
    Description of the illustration DirectMappingSuite.gif

  3. To specify the XPath for this mapping, click the Browse... button in the Editor pane.

    The Choose XPath dialog appears. Use 2 to indicate that you wish to map to a second occurence on the street element.

    Description of DirectMappingXPathSuite.gif follows
    Description of the illustration DirectMappingXPathSuite.gif

Step 10: Map an Object Relationship

Object relationships are mapped to XML elements. This is done using the XML Composite Object Mapping for the single case, and XML Composite Collection Mapping for the collection case. Maps are also supported in the collection case.

Description of CompositeObjectMapping.gif follows
Description of the illustration CompositeObjectMapping.gif

Description of CompositeObjectMappingXPath.gif follows
Description of the illustration CompositeObjectMappingXPath.gif

Mapping a Reference Descriptor is specified when setting up a relationship. When TopLink is performing marshalling/unmarshalling on a Customer object, and the shippingAddress mapping is processed, the metadata for the Address object is used to process that section of the document.

In this example the Customer class has two references to the Address class; the billingAddress and shippingAddress attributes. Both of the corresponding mappings specify Address as the Reference Descriptor. Since the address information for the billingAddress attribute can be found under the billing-address element, the XPath for this mapping is ns1:contact-info/billing-address. The address information for the shippingAddress attribute can be found under the shipping-address element, so the XPath for that mapping is ns1:contact-info/shipping-address.

The location of the XML data is specified as an XPath relative to the schema context set on the descriptor. This XPath location is why TopLink does not require an object for each level of nesting in an XML document.

Description of CompositeObjectMappingReferenceDescriptor.gif follows
Description of the illustration CompositeObjectMappingReferenceDescriptor.gif

Step 11: Map a Collection Relationship

Collection relationships are mapped to XML elements. This is done using the XML Composite Collection Mapping for the single case. Composite collection mappings are similar to composite object mappings.

In this example, if you use a class other the java.util.Vector, you must select the Override Default Class option. The phoneNumbers attribute on the customer class is mapped to a collection phone number objects.

Description of CollectionMapping.gif follows
Description of the illustration CollectionMapping.gif

Step 12: Generate Runtime Metadata

When all the mappings have been completed, the metadata for the TopLink runtime needs to be generated. Save the metadata in a file called CustomerProject.xml in the <DEMO_HOME>/classes directory.

  1. Right-click the CustomerProject in the Navigator pane and select Export > Project Deployment XML....

    The Export Project Deployment XML dialog appears.

  2. Browse to the <DEMO_HOME>/classes directory, specify a file name of CustomerProject.xml, and click OK.

    The TopLink Workbench exports the project metadata into the file and updates the values on the project Options tab.

    Description of DeploymentXML.gif follows
    Description of the illustration DeploymentXML.gif

Step 13: Configure the Session Metadata

To configure the session metadata, follow this procedure:

  1. Select File > New > Sessions Configuration.

  2. Select the sessions configuration in the Navigator pane.

  3. Click the Change... button in the Editor pane.

  4. In the file Save dialog, navigate to the classes directory.

  5. Save the file as sessions.xml.

Description of Session1.gif follows
Description of the illustration Session1.gif

To create a new session, follow this procedure:

  1. Click on the Add Session... button in the Editor pane.

  2. Enter the information in the Create New Session dialog as shown. Enter examples.ox.model in the Name field, select the XML Data Source, and select Database Session.

  3. Click the OK button.

You will use the name of the session later in this How-To document when you instantiate a JAXBContext. The name can be anything, but for this How-To document, we will follow the JAXB convention which uses the package name for the model classes.

Description of CreateSession.gif follows
Description of the illustration CreateSession.gif

You need to configure the session to point to the deployment XML that was generated in "Step 12: Generate Runtime Metadata". To do this, follow this procedure:

  1. Click the Browse... button in the Editor pane.

  2. In the file Open dialog, navigate to the CustomerProject.xml file that was generated.

  3. Click the Open button.

Description of SessionConfigured.gif follows
Description of the illustration SessionConfigured.gif

Step 14: Configure the JAXB Runtime to use the TopLink JAXB Implementation

One of the artifacts generated by a JAXB compiler is a jaxb.properties file. This properties file indicates to the JAXB runtime what vendors implementation must be run. In order to use Plain Ordinary Java Objects (POJOs) with the JAXB runtime you need to manually create this properties file (since there was no compiler step). The jaxb.properties file must correspond to the context path (the package name you called your session). In this How-To document, you used the context path examples.ox.model. This means that you must create the file in the <DEMO_HOME>/classes/examples.ox.model directory. The file must contain the following property: javax.xml.bind.context.factory=oracle.toplink.ox.jaxb.JAXBContextFactory

Step 15: Write a Simple Test Application

Set the required classpath:

You will now make use of the TopLink mapping metadata created in Step 12: Generate Runtime Metadata to unmarshall an XML document from a file (Customer-data.xml) to the customer model, manipulate the data, and then marshal the objects back to XML.

A JAXBContext must first be created. The JAXBContext provides the client's entry point to the JAXB API. The input to the newInstance method corresponds to the name of the session created in Step 13: Configure the Session Metadata.

javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext.newInstance(
    "examples.ox.model"
);

Next you need to unmarshall the XML data to object form. To do this, use the JAXBContext to create an instance of the Unmarshaller class. The Unmarshaller class can accept many types of XML input. For the purpose of this How-To document, you will use a file.

java.io.File file = new java.io.File("./Customer-data.xml");
javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(file);

Now that you have the data in object form you can manipulate it. The following code demonstrates how to add a PhoneNumber. Since you are using normal Java classes you can use the default constructor to instantiate a PhoneNumber instead of using a ObjectFactory generated by a JAXB compiler. Notice how only a few lines of code are required compared to what would be required if this were done using DOM code.

PhoneNumber homePhoneNumber = new PhoneNumber();
homePhoneNumber.setType("home");
homePhoneNumber.setNumber("(613) 555-3333");
customer.getPhoneNumbers().add(homePhoneNumber);

Finally you can marshal the object data back to XML form. To do this, use the JAXBContext to create an instance of the Marshaller class. The Marshaller class can generate many types of XML output. For the purpose of this How-To document, use System.out.

javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(customer, System.out);

Summary

TopLink includes support for mapping your existing Java objects to XML. These mappings use similar principles as object-to-relational mappings created by TopLink. A visual mapping editor called the TopLink Workbench can be used to create and customize these mappings. TopLink provides developers maximum flexibility with the ability to control how their object model is mapped to an XML schema.


Oracle TopLink, 10g Release 3 (10.1.3)

The Programs (which include both the software and documentation) contain proprietary information; they are provided under a license agreement containing restrictions on use and disclosure and are also protected by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly, or decompilation of the Programs, except to the extent required to obtain interoperability with other independently created software or as specified by law, is prohibited.

The information contained in this document is subject to change without notice. If you find any problems in the documentation, please report them to us in writing. This document is not warranted to be error-free. Except as may be expressly permitted in your license agreement for these Programs, no part of these Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose.

If the Programs are delivered to the United States Government or anyone licensing or using the Programs on behalf of the United States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the Programs, including documentation and technical data, shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement, and, to the extent applicable, the additional rights set forth in FAR 52.227-19, Commercial Computer Software—Restricted Rights (June 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City, CA 94065

The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup, redundancy and other measures to ensure the safe use of such applications if the Programs are used for such purposes, and we disclaim liability for any damages caused by such use of the Programs.

Oracle, JD Edwards, PeopleSoft and Siebel are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

The Programs may provide links to Web sites and access to content, products, and services from third parties. Oracle is not responsible for the availability of, or any content provided on, third-party Web sites. You bear all risks associated with the use of such content. If you choose to purchase any products or services from a third party, the relationship is directly between you and the third party. Oracle is not responsible for: (a) the quality of third-party products or services; or (b) fulfilling any of the terms of the agreement with the third party, including delivery of products or services and warranty obligations related to purchased products or services. Oracle is not responsible for any loss or damage of any sort that you may incur from dealing with any third party.