Skip Headers

Oracle Application Server TopLink Mapping Workbench User's Guide
10g (9.0.4)

Part Number B10316-01
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

B
Tutorials

This section contains the following tutorials that illustrate how to use Oracle Application Server TopLink Mapping Workbench.

Before You Begin

The tutorials require classes that are built from the OracleAS TopLink Three Tier example project. This example project is included as part of the complete OracleAS TopLink installation. You must build and run the example before beginning the tutorial. Refer to <ORACLE_HOME>\toplink\doc\examples.htm for complete information.

Introductory Tutorial

In the introductory tutorial, you will create mappings from a simple database three-tier application using OracleAS TopLink Mapping Workbench. You will learn how to:

By the end of the tutorial, you will be able to store data from a Java class into a relational database and access existing database information from Java classes.

Overview

This tutorial project manages the employee database at the ACME Leisure Company. The system tracks each employee's name, address, and phone number.

The system uses these classes:

Figure B-1 illustrates the object model for this system.

Figure B-1 Simple ACME Object Model

Text description of intrmod.gif follows.

Text description of the illustration intrmod.gif

Creating the Database Schema

The ACME employee system stores the employee data in three database tables. Later in this tutorial, you will be able to create these tables from the OracleAS TopLink Mapping Workbench or import them from your database application.


Note:

The column types listed here are generic; the actual column types depend on the database used.


Table B-1 EMPLOYEE Table
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

F_NAME

VARCHAR(40)

L_NAME

VARCHAR(40)

ADDRESS_ID

NUMERIC(15)

Table B-2 ADDRESS Table  
Column Name Column Type Details

ADDRESS_ID

NUMERIC(15)

Primary key

COUNTRY

VARCHAR(80)

STREET

VARCHAR(80)

CITY

VARCHAR(80)

PROVINCE

VARCHAR(80)

P_CODE

VARCHAR(20)

Table B-3 PHONE Table
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

AREA_CODE

CHAR(3)

P_NUMBER

CHAR(7)

TYPE

VARCHAR(15)

Primary key

After creating these ACME database tables, you are ready to begin the tutorial.

Creating a New Project

OracleAS TopLink Mapping Workbench stores project information in the .mwp file and associated folders. Always start an OracleAS TopLink Mapping Workbench project in a new folder.

To create a new project:
  1. Start OracleAS TopLink Mapping Workbench. From the Windows Start menu, select Programs > OracleAS TopLink > Mapping Workbench.

    The splash screen appears, followed by the OracleAS TopLink Mapping Workbench window.

    Figure B-2 OracleAS TopLink Mapping Workbench

    Text description of mwblank.gif follows.

    Text description of the illustration mwblank.gif

  2. Click the New Project button Text description of newprjt.gif follows.

    Text description of the illustration newprjt.gif

    on the toolbar or select File > New Project from the menu. The Create a New Project dialog box appears.

    Figure B-3 Create New Project

    Text description of create.gif follows.

    Text description of the illustration create.gif

  3. From the Create New Project dialog box:

    • In the Database Name field, type INTRO_TUTORIAL_DB.

    • In the Platform field, click Browse button and select the appropriate database platform. Contact your database administrator if you need additional information.

  4. Click OK. The Save As dialog box appears.

    Figure B-4 Save As

    Text description of saveas.gif follows.

    Text description of the illustration saveas.gif

  5. Select the folder in which to save the Employee project.


    Note:

    Always use a new folder to save a project.


  6. In the File Name field, type Employee.mwp.

  7. Click Save to save your work and return to the OracleAS TopLink Mapping Workbench window.

    Figure B-5 OracleAS TopLink Mapping Workbench

    Text description of mwnew.gif follows.

    Text description of the illustration mwnew.gif

  8. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or select File > Save to save the project.


    Note:

    OracleAS TopLink Mapping Workbench does not automatically save your work; remember to save periodically.


Setting the Project's Class Path

Each OracleAS TopLink project uses a class path--a set of directories, .jar files, and .zip files--when importing Java classes and defining object types. In this tutorial, you will use information from the OracleAS TopLink three tier example project. Refer to <ORACLE_HOME>\toplink\doc\examples.htm for complete information.

  1. In the OracleAS TopLink Mapping Workbench, highlight the Employee project in the Navigator pane.

  2. In the Editor pane on the right-hand side of the OracleAS TopLink Mapping Workbench window, click the General tab.

    Figure B-6 General Tab

    Text description of general.gif follows.

    Text description of the illustration general.gif

  3. Click Add Entries. The Add Entry dialog box appears.

    Figure B-7 Add Entries

    Text description of empclsen.gif follows.

    Text description of the illustration empclsen.gif

  4. Browse to the <ORACLE_HOME>\toplink\examples\foundation\
    threetier\stage
    directory and click OK.


    Note:

    If the stage directory does not exist, you must create the OracleAS TopLink Three Tier example project. See "Before You Begin" for more information.


    Figure B-8 General Tab with Class Path Information

    Text description of generlzi.gif follows.

    Text description of the illustration generlzi.gif

  5. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save to save the project.

Enabling Your Java Classes

The Employee model uses three classes:

You must enable the Employee, PhoneNumber, and Address classes (provided in the examples.session.threetier.model package) for this tutorial, as "Generating the Class Definitions" describes.

Table B-4 shows how the classes relate to the database tables.

Table B-4 Employee Classes and Database Tables  
Column Class Attribute Database Type Java Type

EMPLOYEE

Employee

    EMP_ID

id

NUMERIC(15)

BigDecimal

    NAME

name

CHAR(40)

String

    ADDRESS_ID

address

NUMERIC(15)

Address

    not applicable

phoneNumbers

not applicable

Vector

ADDRESS

Address

    ADDRESS_ID

id

NUMERIC(15)

BigDecimal

    COUNTRY

country

VARCHAR(80)

String

    STREET

street

VARCHAR(80)

String

    CITY

city

VARCHAR(80)

String

    PROVINCE

province

VARCHAR(80)

String

    P_CODE

postalCode

VARCHAR(20)

String

PHONE

PhoneNumber

    AREA_CODE

areaCode

CHAR(3)

String

    P_NUMBER

number

CHAR(7)

String

    EMP_ID

owner

NUMERIC(15)

Employee

    TYPE

type

VARCHAR(15)

String


Note:

Supplying each of the class members in OracleAS TopLink-enabled classes with accessor methods is good programming practice. This tutorial provides the get and set methods for each attribute. For example, the Employee class should have an addPhoneNumber() method to allow a new PhoneNumber to store a reference to its parent.


Example B-1 Accessor Method

The following code example illustrates providing accessor methods.

// addPhoneNumber method of the Employee class allows the phoneNumber to set a 
reference to the Employee that owns it.
public void addPhoneNumber(PhoneNumber phoneNumber)
{
    getPhoneNumbers().addElement(phoneNumber);
    phoneNumber.setOwner(this);
}

Generating the Class Definitions

You must generate an OracleAS TopLink descriptor for each Java class in the project.

To create descriptors from the class definition file:
  1. From the Navigator pane, click the Employee project.

  2. Click the Add or Refresh Classes button Text description of addclbt.gif follows.

    Text description of the illustration addclbt.gif

    or choose Selected > Add or Refresh Classes from the menu. The Select Classes dialog box appears.

    You can also create descriptors by right-clicking on the project in the Navigator pane and selecting Add or Refresh Classes from the pop-up menu.

    Figure B-9 Select Classes

    Text description of selectcl.gif follows.

    Text description of the illustration selectcl.gif

  3. Locate the examples.sessions.threetier.model package. Click the plus sign ( Text description of plus.gif follows.

    Text description of the illustration plus.gif

    ) to expand that package (or double-click the name to expand the package).

    Figure B-10 Demo Classes

    Text description of selclsex.gif follows.

    Text description of the illustration selclsex.gif

  4. Highlight the Address class and click the Text description of arrow.gif follows.

    Text description of the illustration arrow.gif

    button. OracleAS TopLink copies the Address class to the Selected Classes pane.

    Figure B-11 Selected Class

    Text description of selctadd.gif follows.

    Text description of the illustration selctadd.gif

  5. Repeat Step 4 for Employee and PhoneNumber classes in that package. (Or, highlight both classes using Shift+click or Ctrl+click as necessary, and click Text description of arrow.gif follows.

    Text description of the illustration arrow.gif

    once to import all the remaining classes.)

  6. Click OK to import the classes. OracleAS TopLink creates a descriptor for each class and an unmapped mapping for each attribute. The descriptors and their attributes appear in the Navigator pane.


    Note:

    If an error occurs, check that the given classes are included in the class path and that JDK has been installed correctly.


    Figure B-12 OracleAS TopLink Mapping Workbench with Employee Project

    Text description of mwemp1.gif follows.

    Text description of the illustration mwemp1.gif

    Figure B-12 identifies the following user-interface elements:

    1. Package

    2. Class/descriptors

  7. Save your changes. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Logging Into the Database

You can enter database table information directly from OracleAS TopLink Mapping Workbench or import the tables from the database. You must log into the database to obtain the table information and to generate table files.


Note:

You must include your database driver on the system classpath - not the OracleAS TopLink Mapping Workbench project classpath.


  1. Select the INTRO_TUTORIAL_DB database object in the Navigator pane. The Database Editor property sheet appears in the Editor pane of the OracleAS TopLink Mapping Workbench window.

    Figure B-13 Database Properties

    Text description of dblogin.gif follows.

    Text description of the illustration dblogin.gif

  2. Click Add to create a new database login.

  3. In the Defined Login area, select the newly added login. Contact your database administrator for the necessary database login information (driver, URL, username, and password).

  4. Click the Log In to Database button Text description of loginbtn.gif follows.

    Text description of the illustration loginbtn.gif

    or choose Selected > Log In to Database from the menu. The database icon changes to  Text description of dblogbtn.gif follows.

    Text description of the illustration dblogbtn.gif

    .


    Note:

    OracleAS TopLink Mapping Workbench supports connecting to the database through JDBC. Make sure you have installed, configured, and tested your JDBC driver before attempting to connect.


If OracleAS TopLink Mapping Workbench is unable to connect to the database, contact your database administrator to ensure that the database login parameters have been entered correctly and your JDBC driver has been installed correctly. If problems persist, test your driver connectivity. See the Appendix C, "Troubleshooting" for details.

Creating Tables

You can enter database table information (as "Creating the Database Schema" specifies) directly from OracleAS TopLink Mapping Workbench or import the tables from the database.

Creating Tables Using the OracleAS TopLink Mapping Workbench

Use this procedure to create the database tables from the OracleAS TopLink Mapping Workbench.


Caution:

Do not use this procedure if you plan to import the tables from a database.


Creating the Table Definitions

Use this procedure to create table definitions using the OracleAS TopLink Mapping Workbench. Later, you can create the actual tables on the database.

To create the tables:
  1. Select the database in the Navigator pane and click the Add New Table button Text description of addtable.gif follows.

    Text description of the illustration addtable.gif

    or right-click the database in the Navigator pane, and choose Add New Table. The New Table dialog box appears.

  2. Type ADDRESS for the table name, and click OK.


    Note:

    Leave the Catalog and Schema fields blank.


  3. Click the Fields tab in the Editor pane.

  4. Click Add to add each database field for the ADDRESS table. Refer to the tables in "Creating the Database Schema" for the correct field information. Be sure to indicate the primary key(s) for each table.


    Note:

    Use the scroll bar to view additional fields for each database field (such as the Primary Key). See "Preparing the Primary Keys" for more information.


    Figure B-14 Database Fields Tab

    Text description of fldaddr.gif follows.

    Text description of the illustration fldaddr.gif

  5. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Repeat this procedure for the EMPLOYEE and PHONE tables.

Creating the Tables on the Database

After defining the tables in OracleAS TopLink Mapping Workbench, you can automatically create the tables on the database.

To create tables on the database:
  1. Right-click one of the database tables in the Navigator pane, and choose Create on Database > All Tables from the pop-up menu. The system displays a message indicating that the three tables were created.


    Note:

    To use the Create on Database option, you must be logged into the database.


    If the Confirm Replace dialog box appears, it means that an existing table on the database has the same name. Check with your database administrator before replacing any table. The existing table may have been created by:

    • Someone else doing the tutorial previously (in which case you could click the Yes to All button safely)

    • Someone using the same database name for a business project (in which case you should not replace it)

  2. Click OK to close the dialog box and return to the OracleAS TopLink Mapping Workbench window.

  3. On the toolbar, click the Logout of Database button Text description of logotbtn.gif follows.

    Text description of the illustration logotbtn.gif

    or choose Selected > Log Out from the menu.

  4. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Continue with "Mapping Classes and Tables in the Descriptor".


Note:

OracleAS TopLink Mapping Workbench can generate Data Definition Language (DDL) creation scripts that can be used to create tables on the desired database.

If the table creation fails, there might have been a problem with the DDL, or you may not have permission to create tables on the database. Make sure you set the target database to the correct database platform on login. Because the DDL may not be compatible with some databases, you may have to edit the generated DDL and execute the DDL manually.

In addition, ensure that the Database Platform field on the Database property sheet (see Figure B-13) matches your database driver information.


Importing Tables from the Database

Use this procedure if you have already created tables in your database and want to import these tables directly into the OracleAS TopLink Mapping Workbench.


Caution:

Do not use this procedure if you plan to create the tables directly from OracleAS TopLink Mapping Workbench.


To import tables from the database:
  1. Click the Login to Database button Text description of loginbtn.gif follows.

    Text description of the illustration loginbtn.gif

    or choose Selected > Login from the menu.

  2. Select the database in the Navigator pane and click the Add or Update Existing Tables from Database button Text description of addtbldb.gif follows.

    Text description of the illustration addtbldb.gif

    , or right-click the database and choose Add or Update Existing Tables From Database from the pop-up menu.

    The Import tables from database dialog box appears.

    Figure B-15 Import Tables from Database

    Text description of importdb.gif follows.

    Text description of the illustration importdb.gif

    Figure B-15 calls out the following user-interface elements:

    1. Use the filters to specify database tables to select for import.

    2. The Available Tables displays the database tables that match the filter.

  3. Click the Get Table Names button to display all tables in the database.


    Note:

    You can use the table filters to specify which database tables are available for import. For this tutorial, leave the filters as their default values.


  4. Select the ADDRESS table in the Available Tables pane and then click the Text description of arrow.gif follows.

    Text description of the illustration arrow.gif

    button. The ADDRESS table moves to the Selected Tables pane.

  5. Repeat Step 4 for the EMPLOYEE and PHONE tables.

  6. Click OK to add the selected tables to the Employee project.

  7. To display the details of the imported tables, select a table in the Navigator pane and click the Fields tab in the Editor pane.

  8. Click the Log Out of Database button Text description of logotbtn.gif follows.

    Text description of the illustration logotbtn.gif

    or choose Selected > Log Out of Database from the menu.

  9. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Continue with "Mapping Classes and Tables in the Descriptor".

Mapping Classes and Tables in the Descriptor

When you create a new project and generate class definitions, OracleAS TopLink Mapping Workbench automatically creates descriptors. However, these descriptors do not contain any information about how the classes are associated with the tables. This section describes how to store associations in a descriptor, which can then be used by a Java application to make the classes persistent.

This section contains procedures to map the classes to tables for the ACME project. After mapping the descriptors, you can access the database from a Java application.

Mappings

The OracleAS TopLink mapping describes the way an attribute is stored in, and retrieved from, a database. For example, the name attribute of the Employee class maps to the NAME column of the EMPLOYEE table.

Descriptors

A descriptor stores the class-to-table mappings for a class. OracleAS TopLink Mapping Workbench stores the descriptors in XML files in the Descriptor directory. At run time, OracleAS TopLink creates instances of the Descriptor class for each of the descriptor files and stores them in a database session.

Mapping Classes to Tables

Use this procedure to associate the Java classes with database tables.

To map Java classes to a table:
  1. Select the Address descriptor from the Navigator pane.

  2. Click the Descriptor Info tab of the Editor pane.

  3. In the Associated Table drop-down menu, choose the Address table.

    Figure B-16 Descriptor Info Tab

    Text description of descinfo.gif follows.

    Text description of the illustration descinfo.gif


    Note:

    A warning message appears in the status bar, indicating that the primary key fields are unmapped. This is addressed later in the tutorial.


  4. Repeat steps 1 - 3 to map:

    • Employee class to the EMPLOYEE table

    • PhoneNumber class to the PHONE table

  5. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Although you have mapped the descriptors to specific database tables, the class attributes have not yet been mapped to the tables' columns. You will map the attributes later in this tutorial.

Preparing the Primary Keys

A table's primary key is the field (or fields) used to uniquely identify its records. The PHONE table has a compound primary key (EMP_ID and TYPE fields).

Database tables often use a sequence number as the primary key. Sequence numbers are sequential, artificially generated fields, outside of the problem domain, that uniquely identify a record. OracleAS TopLink supports sequence numbers through the database's native support, such as in Oracle and Sybase, or by maintaining a sequence table. If sequence numbers are enabled for a class, they are generated and incremented whenever an object of that class is inserted into a database.

To specify the primary key:
  1. In the Navigator pane, select the ADDRESS database table.

  2. On the Fields tab of the Editor pane, make sure the ADDRESS_ID column is selected as a Primary Key.

    Figure B-17 Database Table Fields Tab

    Text description of fldaddr.gif follows.

    Text description of the illustration fldaddr.gif

  3. Repeat Step 1 - 2 for the other tables:

    • EMPLOYEE table - Set the EMP_ID field as the primary key.

    • PHONENUMBER table - Set both the EMP_ID and TYPE fields as primary keys.

  4. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Setting the Sequence Table

The ACME system uses sequence numbers for the EMPLOYEE and ADDRESS tables. You must explicitly create a sequence table, then apply it to your project.

To create a sequence table:
  1. Select the database in the Navigator pane, and log into the database by clicking the Login button Text description of loginbtn.gif follows.

    Text description of the illustration loginbtn.gif

    or by right-clicking on the database in the Navigator and choosing Login from the pop-up menu.

  2. Select Database in the Navigator pane and click the Add New Table button Text description of addtable.gif follows.

    Text description of the illustration addtable.gif

    . The New Table dialog box appears.

    Figure B-18 New Table

    Text description of newtable.gif follows.

    Text description of the illustration newtable.gif

  3. Create a table named SEQUENCE. Leave Catalog and Schema blank, unless required by your specific database.

  4. Add the following fields to the table:

  5. Set the SEQ_NAME field as the primary key.

  6. Log out of the database by right-clicking the Database in the Navigator pane and choosing Log Out from the pop-up menu.

  7. Select the Project in the Navigator pane.

  8. Select the project's Sequencing tab in the Editor pane.

    Figure B-20 Sequencing Tab

    Text description of seqtut.gif follows.

    Text description of the illustration seqtut.gif

  9. Select Use Custom Sequence Table and use the drop lists to choose the Name, Sequence Name Field, and Sequence Counter Field, as Figure B-20 illustrates.

  10. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.


    Note:

    You will set the individual sequence names for each table later.


Implementing Direct-to-Field Mappings

The Address class does not reference any other classes. Its attributes map directly to database fields as a direct-to-field mapping.

To map the Address class attributes directly to the ADDRESS columns:
  1. Expand the Address descriptor in the Navigator pane.

  2. Click the city attribute.

  3. Click the Direct-to-Field mapping button Text description of dtfmpbtn.gif follows.

    Text description of the illustration dtfmpbtn.gif

    on the mapping toolbar. The Direct-to-Field mapping tab appears in the Editor pane.

  4. Use the Database Field drop-down list to choose the CITY field.

    Figure B-21 Direct-to-Field Mapping General Tab

    Text description of dfcity.gif follows.

    Text description of the illustration dfcity.gif

  5. Repeat steps 2 - 4 to map the remaining attributes in the ADDRESS table.

    • Map the COUNTRY attribute to COUNTRY field.

    • Map the ID attribute to ADDRESS_ID field.


      Note:

      When you map the ADDRESS_ID field (the primary key), the OracleAS TopLink Mapping Workbench removes the warning icon for the Address descriptor.


    • Map the POSTALCODE attribute to P_CODE field.

    • Map the PROVINCE attribute to PROVINCE field.

    • Map the STREET attribute to STREET field.

  6. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Setting the Sequence Name

The Address and Employee classes use nonnative sequencing for primary keys.


Note:

The sequence name is the value of a row stored in the sequence table. When you create tables for your own projects, you must insert this row into the table using the OracleAS TopLink SchemaManager.


To set the sequencing for the Address and Employee classes:
  1. Select the Address descriptor in the Navigator pane.

  2. Select the Descriptor Info in the Editor pane.

  3. Select the Use Sequencing check box.

  4. In the Name field, type ACME_ADDRESS and use the drop lists to choose the Table and Field, as in Figure B-22.

    Figure B-22 Descriptor Info Tab

    Text description of seqname.gif follows.

    Text description of the illustration seqname.gif

  5. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

  6. Repeat steps 1 - 4 to set the sequencing for the Employee class. Use ACME_EMPLOYEE as the Name, and choose EMPLOYEE and EMP_ID from the Table and Field drop-down lists, respectively.

  7. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu

When the descriptors are registered with a database session, this information is entered into the SEQUENCE table. The session tracks the sequencing information.

Creating One-to-One Mappings Between Objects

In the Employee class, the name and id attributes map directly to the EMPLOYEE table columns. The phoneNumbers and address attributes refer to other Java classes, rather than referring directly to columns in the database.

  1. Map the firstName and lastName attributes as a direct-to-field mapping to the F_NAME and L_NAME fields, respectively.

  2. Map the id attribute as a direct-to-field mapping to the EMP_ID field (the primary key).

Only one home address is associated with each employee, so the address attribute requires a one-to-one mapping with the Address class. Figure B-23 illustrates a sample one-to-one mapping.

Figure B-23 One-to-One Mappings

Text description of 11mapfig.gif follows.

Text description of the illustration 11mapfig.gif

To create a one-to-one mapping
  1. Select the Employee's address attribute in the Navigator pane, then click the One-to-one Mapping button Text description of 11mapbtn.gif follows.

    Text description of the illustration 11mapbtn.gif

    on the mapping toolbar.

    The Editor pane displays the appropriate information for a one-to-one relationship to be specified.

    Figure B-24 One-to-One Mapping General Tab

    Text description of chseref.gif follows.

    Text description of the illustration chseref.gif

  2. Use the Reference Descriptor drop-down list in the to select Address as the reference descriptor.

  3. Select the Use Indirection check box.

  4. Ensure that the Private Owned check box is enabled.

    This allows the Address object to be created, updated, or deleted automatically when the Employee owning it is changed.

Foreign Key References

One-to-one mappings use the relational database concept of foreign keys to access other classes stored in the database. You must specify the foreign key information in the descriptor so that OracleAS TopLink knows how to search for a referenced object, as Figure B-23 shows.

  1. Click the Table Reference tab.

  2. Create a new table reference by clicking the New button.

  3. In the New Reference dialog box, create a reference whose:

    • Name is EMPLOYEE_ADDRESS

    • Source table is EMPLOYEE

    • Target table is ADDRESS


      Note:

      If you leave the Name field blank, OracleAS TopLink automatically builds the name as <SourceTable>_<TargetTable>.


    Select the On Database option if you want to create the reference on the database when you create the tables. OracleAS TopLink does not require that you actually have the constraint on the database, but you may wish to do this for other reasons. Consult your database administrator for more information.


    Note:

    The mapping is from the EMPLOYEE table, ADDRESS_ID attribute to the ADDRESS table.


  4. Choose EMPLOYEE_ADDRESS from the Table Reference drop-down list.

  5. Click the Add button to define the foreign key fields.

    • In the Source Field column, choose ADDRESS_ID (foreign key).

    • In the Target Field column, choose ADDRESS_ID (primary key).

    • Leave the Target Foreign Key option unchecked.

      Figure B-25 One-to-One Mapping Table Reference Tab

      Text description of addrref.gif follows.

      Text description of the illustration addrref.gif

  6. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.

Creating One-to-Many Mappings

To map an attribute to a Java collection such as a Vector, the application must make a one-to-many mapping for the class owning the collection, and a one-to-one mapping back from the class being referenced. The one-to-one mapping in the referenced class is implemented as a foreign key to the source class.

Figure B-26 One-to-Many Mappings

Text description of 1mmapfig.gif follows.

Text description of the illustration 1mmapfig.gif

In this tutorial, the Employee project requires:

To map the phoneNumbers attribute:
  1. Expand the Employee class in the Navigator pane.

  2. Select the phoneNumbers attribute.

  3. Click the One-to-many Mapping button Text description of 1mmapbtn.gif follows.

    Text description of the illustration 1mmapbtn.gif

    on the mapping toolbar. The Editor pane changes to allow you to specify the appropriate information for a one-to-many relationship.

  4. Use the Reference Descriptor drop-down list to choose PhoneNumber.

    Figure B-27 One-to-Many Mapping General Tab

    Text description of chsephon.gif follows.

    Text description of the illustration chsephon.gif

  5. Click the Table Reference tab, and add a new reference by clicking New.

    • Create a new reference named PHONE_EMPLOYEE with a source table of PHONE and a target table of EMPLOYEE and click OK.

    • In the Table Reference drop-down list, choose the PHONE_EMPLOYEE.

    • Click the Add button on the Table Reference tab to add a foreign key relationship. Set the Source (foreign key) field to EMP_ID and the Target (primary key) field to EMP_ID.

      Figure B-28 One-to-Many Mapping Table Reference Tab

      Text description of phtabref.gif follows.

      Text description of the illustration phtabref.gif

  6. Save your changes. Click the Save Project button Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    or choose File > Save from the menu.


    Note:

    Leave the remaining attributes of the Employee descriptor as unmapped. You will use them in the Advanced tutorial.


To map the PhoneNumber class to the Employee class:

After mapping the Employee descriptor, use this procedure to map the one-to-one back reference:

  1. Map the owner attribute of the PhoneNumber descriptor as a one-to-one mapping to the Employee class (refer to "Creating One-to-One Mappings Between Objects").

  2. Select EMPLOYEE as the Reference Descriptor.


    Note:

    You do not need to create a new table reference. Select the same PHONE_EMPLOYEE reference you created when you mapped the one-to-many from Employee to PhoneNumber.


  3. Map the remaining attributes in the Phone descriptor as direct-to-field mappings (refer to "Implementing Direct-to-Field Mappings").

  4. Remove all unmapped attributes in the Employee descriptor. Right-click the attribute and choose Remove from the pop-up menu.

    You can also remove attributes by choosing Selected > Remove from the menu.

Setting Up Database Sessions

A database session in OracleAS TopLink represents an application's dialog with a relational database. The DatabaseSession class keeps track of the following information:

An application uses the session to log in to the database and perform read and write operations on the objects stored therein. The session's lifetime is normally the same as the lifetime of the application.

OracleAS TopLink includes a test class so that you can test the descriptor mappings that you have created for this introductory tutorial. This class, Demo, among other things, tests the validity of the descriptors and logs into the database.

Logging Into a Database

To log into a database, an application must first read the project file into a Project instance. The Project creates the DatabaseSession and connects through login. The OracleAS TopLink Mapping Workbench can generate the project file (Employee.xml in this example), including the login information. The following code fragment illustrates this approach.

Example B-2 Logging in and Creating a Project Example Code

The following code example illustrates creating the EMPLOYEE project.

...
    import oracle.toplink.sessions.*;
    ...
    Project builderProject = 
oracle.toplink.tools.workbench.XMLProjectReader.read("C:\\oracle\\toplink\\
tutorials\\intro\\Employee.xml");     DatabaseSession session = builderProject.createDatabaseSession();     session.login(); // or, session.login(userName, password);     ...

See the loginToDatabase() method, in the Demo class, for a complete method.

Creating the Tables in Code

You can use OracleAS TopLink Mapping Workbench to create database tables. OracleAS TopLink can also create tables using the SchemaManager class. To use this method of creating tables, you must have already obtained a valid login.

The following example illustrates how to create the EMPLOYEE table after having logged into the database. The method createTables() on the Demo class contains sample code that uses the schema manager to create all the required tables for the introductory tutorial.

Example B-3 Creating Tables

The following code example illustrates creating the EMPLOYEE table.

import oracle.toplink.tools.schemaframework.*;
    import java.math.*;
    
    // Create table definition which supplies information about the table to be 
created.
    TableDefinition employeeTable = new TableDefinition();
    employeeTable.setName("EMPLOYEE");
    employeeTable.addIdentityField("EMP_ID", BigDecimal.class, 15);
    employeeTable.addField("NAME", String.class, 40);
    employeeTable.addField("ADDRESS_ID", BigDecimal.class, 15);
    
    // Create the table in the database.
    SchemaManager schemaManager = new SchemaManager(session);
    schemaManager.replaceObject(employeeTable); 
    
    // Create an empty table named SEQUENCE if it is not already there. This is 
used to hold the sequence number information such as name and counter.
    schemaManager.createSequences(); 

Using Descriptors in an Application

After creating the descriptor files, you must write Java code to register the files with the OracleAS TopLink session. After registering the files, the application can read and write Java class instances from the database.

Transactions and Units of Work

A transaction is a set of database operations that can be either committed (accepted) or rolled back (undone). Transactions can be as simple as inserting an object into a database, but also allow complex operations to be committed or rolled back as a single unit. Unsuccessful transactions can be discarded, leaving the database in its original state.

A unit of work is an object that simplifies the transaction process and stores transaction information for its registered persistent objects. The unit of work enhances database commit performance by updating only the changed portions of an object. Units of work are the preferred method of writing to a database in OracleAS TopLink.

To use a unit of work, create an instance of UnitOfWork and register the desired persistent objects. The registering process returns clones that can be modified. After changes are made to the clones, use the commit() method to commit an entire transaction. The unit of work inserts new objects or updates changed objects in the database, as Figure B-29 illustrates.

If an error occurs when writing the objects to the database, a DatabaseException is thrown, and the unit of work is rolled back to its original state. If no database error occurs, the original objects are updated with the new values from the clones.

Figure B-29 Unit of Work Example

Text description of uow.gif follows.

Text description of the illustration uow.gif

Reading and Writing Java Class Instances

Sessions can read instances from the database using the readObject() method. Database sessions can write instances to the database using the writeObject() method, but note that write is neither required nor used when employing a unit of work. An application typically uses the session to read the instances of a given class from the database and determines which of the instances require changes. The instances requiring changes are then registered with a unit of work. After the changes have been made, the unit of work is used to commit only the changed objects to the database.

This model provides the optimum performance for most applications. Read performance is optimized by using the session because the unit of work does not have to keep track of objects that do not change. Write performance is optimized because the unit of work keeps track of transaction information and writes only the changed portions of an instance to the database.

Using a Unit of Work to Write an Object

After the descriptors have been registered with the session, you are ready to read and write objects to the database. Objects are registered with a unit of work and then committed to the database.

The code fragment in the following example is a continuation of the fragment in Example B-3 and uses the session created there.

Example B-4 Unit of Work

The following code example illustrates using a unit of work to write an object.

//Create an Employee object for the company president, as well as the associated 
personal information objects.
Employee president = new Employee();

Address presidentHome = new Address();
presidentHome.setStreet("601-1140 Meadowlands Dr.");
presidentHome.setCity("Ottawa");
presidentHome.setPostalCode("K2E 6J6");
presidentHome.setProvince("ON");
presidentHome.setCountry("Canada");

PhoneNumber homePhone = new PhoneNumber();
homePhone.setType("Home");
homePhone.setAreaCode("555");
homePhone.setNumber("555-1234");

PhoneNumber businessPhone = new PhoneNumber();
businessPhone.setType("Business");
businessPhone.setAreaCode("555");
businessPhone.setNumber("555-5678");

president.setName("John Smith");
president.setAddress(presidentHome);
president.addPhoneNumber(homeNumber);
president.addPhoneNumber(businessPhone);

//Register objects with a new unit of work. Registered objects will return a 
clone which should be used to make changes to the object.
UnitOfWork unitOfWork;
unitOfWork = session.acquireUnitOfWork();
Employee tempPresident = (Employee)unitOfWork.registerObject(president);

//Register any other objects, or change registered objects.
tempPresident.setName("Johnny Smith");

//Commit the objects to the database.
unitOfWork.commit(); 

Using a Session to Read an Object

To change the information in the database, the application must create an Expression that contains information about the query to be made. The session then searches the database for an object that matches the query and returns the instance. The returned object is registered with the unit of work, and the application makes changes to the object. The application then commits the changes to the database using the commit() method.

Example B-5 Session

The following code example illustrates using a session to read an object.

//Import the Expression classes.
import oracle.toplink.expressions.*;

//Import the other classes. Create a session and login. Create a query 
expression to find the database object.
ExpressionBuilder builder = new ExpressionBuilder();
Expression expression = builder.get("name").equal("John Smith");

//Read the object from the database using the query expression.
Employee president = (Employee) session.readObject(Employee.class, expression);

//Register the object with a new unit of work.
UnitOfWork unitOfWork = session.acquireUnitOfWork();
Employee tempPresident = (Employee)unitOfWork.registerObject(president);

//Make the change to the object.
tempPresident.setName("Johnny Smith");

//Commit the change to the database. Only the NAME field is actually updated.
unitOfWork.commit(); 

Conclusion

This introductory tutorial explained the basic steps required to create a Java project that accesses a relational database through OracleAS TopLink. The main concepts explained include:

Advanced Tutorial

In this advanced tutorial, you will improve the ACME Employment Management System (built in the introductory tutorial) to manage additional information. You will update the introductory application with new project information and reuse existing components from previous applications.

You will also learn how to:

This advanced tutorial adds the ability to track employees' current projects, managers, and contract period. You will reuse components from the introductory tutorial.

In addition to the Employee, Address, and PhoneNumber classes from the introductory tutorial (see "Overview"), the advanced tutorial uses these classes:

Figure B-1 illustrates the object model for the advanced tutorial.

Figure B-30 Advanced Tutorial Object Model

Text description of advmodel.gif follows.

Text description of the illustration advmodel.gif

Creating the Database Schema

The advanced ACME employee system stores the employee data in the following database tables. To use this tutorial, create these tables in your database application. Table B-13 describes how each class relates to the database tables.

The column types listed here are generic; the actual column types depend on the database used.

Table B-5 EMPLOYEE Table   
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

F_NAME

VARCHAR(40)

L_NAME

VARCHAR(40)

ADDR_ID

NUMERIC(15)

GENDER

CHAR(1)

START_DATE

DATE

END_DATE

DATE

START_TIME

TIME

END_TIME

TIME

MANAGER_ID

NUMERIC(15)

VERSION

NUMERIC(15)

Table B-6 SALARY Table
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

SALARY

NUMERIC(10)

Table B-7 ADDRESS Table 
Column Name Column Type Details

ADDRESS_ID

NUMERIC(15)

Primary key

COUNTRY

VARCHAR(80)

STREET

VARCHAR(80)

CITY

VARCHAR(80)

PROVINCE

VARCHAR(80)

P_CODE

VARCHAR(20)

Table B-8 PHONE Table
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

AREA_CODE

CHAR(3)

P_NUMBER

CHAR(7)

TYPE

VARCHAR(15)

Primary key

Table B-9 PROJECT Table
Column Name Column Type Details

PROJ_ID

NUMERIC(15)

Primary key

DESCRIP

VARCHAR(200)

PROJ_NAME

VARCHAR(30)

PROJ_TYPE

CHAR(1)

LEADER_ID

NUMERIC(15)

VERSION

NUMERIC(15)

Table B-10 LPROJECT Table
Column Name Column Type Details

PROJ_ID

NUMERIC(15)

Primary key

BUDGET

NUMERIC(10,2)

MILESTONE

TIMESTAMP

Table B-11 RESPONS Table
Column name Column type Details

EMP_ID

NUMERIC(15)

Primary key

DESCRIP

VARCHAR(200)

Table B-12 PROJ_EMP Table Between PROJECT and EMPLOYEE
Column Name Column Type Details

EMP_ID

NUMERIC(15)

Primary key

PROJ_ID

NUMERIC(15)

Primary key

Table B-13 Relationships Between Classes and Database Table  
Column Class Attribute Database Type Java Type

EMPLOYEE

Employee

    EMP_ID

id

NUMERIC(15)

BigDecimal

    F_NAME

firstName

VARCHAR(40)

String

    L_NAME

lastName

VARCHAR(40)

String

    ADDR_ID

address

NUMERIC(15)

Address

    not applicable

phoneNumbers

not applicable

Vector

    GENDER

gender

CHAR(1)

String

    START_TIME

normalHours[0]

TIME

Time

    END_TIME

normalHours[1]

TIME

Time

    MANAGER_ID

manager

NUMERIC(15)

Employee

    not applicable

managedEmployees

not applicable

Vector

    not applicable

projects

not applicable

Vector

    see Employment Period

period

not applicable

EmploymentPeriod

SALARY

Employee

    EMP_ID

not applicable

NUMERIC(15)

not applicable

    SALARY

salary

NUMERIC(10)

int

EMPLOYEE

EmploymentPeriod

    START_DATE

startDate

DATE

Date

    END_DATE

endDate

DATE

Date

RESPONS

Employee

    EMP_ID

not applicable

NUMERIC(15)

not applicable

    DESCRIP

responsibilitiesList

VARCHAR(200)

String

    PROJECT

LargeProject and SmallProject

    PROJ_ID

id

NUMERIC(15)

BigDecimal

    DESCRIP

description

VARCHAR(200)

String

    LEADER_ID

teamLeader

NUMERIC(15)

Employee

    PROJ_NAME

name

VARCHAR(30)

String

    PROJ_TYPE

not applicable

CHAR(1)

not applicable

    VERSION

not applicable

NUMERIC(15)

not applicable

LPROJECT

LargeProject

    PROJ_ID

not applicable

NUMERIC(15)

not applicable

    BUDGET

budget

NUMERIC(10,2)

double

    MILESTONE

milestoneVersion

TIMESTAMP

TimeStamp

ADDRESS

Address

    ADDRESS_ID

id

NUMERIC(15)

BigDecimal

    COUNTRY

country

VARCHAR(80)

String

    STREET

street

VARCHAR(80)

String

    CITY

city

VARCHAR(80)

String

    PROVINCE

province

VARCHAR(80)

String

    P_CODE

postalCode

VARCHAR(20)

String

PHONE

PhoneNumber

    AREA_CODE

areaCode

CHAR(3)

String

    P_NUMBER

number

CHAR(7)

String

    EMP_ID

owner

NUMERIC(15)

Employee

    TYPE

type

VARCHAR(15)

String

PROJ_EMP

*Relation Table*

    PROJ_ID

not applicable

NUMERIC(15)

not applicable

    EMP_ID

not applicable

NUMERIC(15)

not applicable

Creating a New Project

  1. Create a new project for the Advanced Tutorial as "Creating a New Project" describes.

    • For the database name, use ADVANCED_TUTORIAL_DB.

    • For the project name, use Advanced Tutorial.

  2. Set the project's class path to include the examples.session.threetier.model package. See "Setting the Project's Class Path".

  3. Enable the following classes in the examples.session.threetier.model package, and generate a TopLink descriptor for each Java class as "Generating the Class Definitions" describes:

    • Address

    • Employee

    • EmploymentPeriod

    • LargeProject

    • PhoneNumber

    • BaseProject

    • SmallProject

    Table B-13 shows how the classes relate to the database tables.

  4. Log into the database as "Logging Into the Database" describes to create or import the database information.

    Select one of the following methods to add database information:

    Refer to Table B-5 through Table B-12 for complete database information.

Mapping Classes to Tables

Map each Java class in the Advanced tutorial to a database table as "Mapping Classes to Tables" describes.

Map this class... To this database table...

Address

ADDRESS

Employee

EMPLOYEE

LargeProject

LPROJECT

PhoneNumber

PHONENUMBER

BaseProject

PROJECT

Ensure that the primary keys are correctly indicated, as Table B-5 through Table B-12 specify.


Note:

A warning message appears indicating that you have not yet mapped the attributes. This is addressed later in the tutorial.


Using the Automap Tool

TopLink can automatically map class attributes to similarly named database tables. This Automap function creates mappings only for unmapped attributes--it does not change previously defined mappings.

You can automap classes for an entire project or for specific tables.


Note:

Although Automap correctly maps most one-to-one and direct-to-field mappings, examine each mapping for valid and correct information. You may need to add or change some mappings.


To Automap the Address descriptor:
  1. Choose the Address class in the Navigator pane and click the Descriptor Info tab in the Editor pane.

  2. In the Associated Table drop-down list, choose the ADDRESS table.

    You must associate the class with a table before using the Automap tool.

  3. Right-click the Address class in the Navigator pane and choose Automap from the pop-up menu.

    You can also automap descriptors by choosing Selected > Automap from the menu.

The system automatically maps each attribute to the appropriate database table. Do not Automap any other classes. You will manually map these classes later in this tutorial.

Implementing Indirection

Indirection allows you to retrieve objects from the database as needed.

Using indirection can be a great performance benefit and we strongly recommended using it. See "Working with Indirection" for more information.

Preparing Java Code for Indirection

To prepare your object model for indirection, you must alter the application slightly:

You can implement indirection using direct access or method access.

If the instance variable returns a Vector instead of an object, then define the value holder in the constructor as follows:

addresses = new ValueHolder(new Vector());

In the following examples, the Employee class uses indirection with method access for its one-to-one mapping to Address. The class definition is modified so that the address attribute of Employee is a ValueHolderInterface instead of an Address. In both examples, the application uses the getAddress() and setAddress() methods to access the Address object.

Example B-6 Indirection Examples

The following example illustrates code before using indirection.

protected Address address;
    public Employee() {
        address = null;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }

The following example illustrates the same code after using indirection.

protected ValueHolderInterface address;
    public Employee() {
        address = new ValueHolder();
    }
    public Address getAddress() {
        return (Address)address.getValue();
    }
    public void setAddress(Address address) {
        this.address.setValue(address);
    }

The indirection example could also use method access instead of direct access. This would be implemented by adding getAddressValueHolder() and setAddressValueHolder() methods.

Implementing Indirection in the OracleAS TopLink Mapping Workbench

After modifying the code, update the OracleAS TopLink Mapping Workbench descriptors to use indirection.

To implement indirection in the Workbench:
  1. Map the one-to-one and one-to-many mappings for each class as normal.

  2. On the General tab for each mapping, select the Use Indirection option.

    Figure B-31 General Tab of a Mapping

    Text description of 11empatt.gif follows.

    Text description of the illustration 11empatt.gif

Implementing Indirection in the Tutorial

The following attributes in the Advanced tutorial sample code have been implemented using ValueHolderInterfaces:

Employee

PhoneNumber

BaseProject

When you create mappings for these attributes, be sure to enable the Use Indirection option.

Implementing a One-to-One Self Relationship

Some object models require a class to reference another instance of the same class. In the advanced tutorial, the Manager attribute in the Employee class references another employee (see Figure B-1).

To map the manager attribute:
  1. Select the Employee's manager attribute in the Navigator pane, then click the One-to-One Mapping button Text description of 11mapbtn.gif follows.

    Text description of the illustration 11mapbtn.gif

    on the mapping toolbar.

    The Editor pane displays the appropriate information for a one-to-one relationship to be specified.

  2. Use the Reference Descriptor drop-down list on the General tab to choose Employee as the reference descriptor.

    Figure B-32 One-to-One Mapping General Tab

    Text description of 11mpmgr.gif follows.

    Text description of the illustration 11mpmgr.gif

  3. Select the Use Indirection option. See "Implementing Indirection in the Tutorial".

  4. Click the Table Reference tab.

    Figure B-33 One-to-One Mapping Table Reference Tab

    Text description of 11manref.gif follows.

    Text description of the illustration 11manref.gif

  5. Create a new table reference by clicking the New button.

  6. In the New Reference dialog box, create a reference whose:

    • Name is EMPLOYEE_EMPLOYEE

    • Source table is EMPLOYEE

    • Target database is EMPLOYEE


      Note:

      If you leave the Name field blank, then TopLink automatically names the table as <SourceTable>_<TargetTable>.


  7. Select EMPLOYEE_EMPLOYEE (created in step 5 from the Table Reference drop-down list.

  8. Click the Add button to define the foreign key fields.

    • In the Source Field column, choose MANAGER_ID (foreign key) field.

    • In the Target Field column, choose EMP_ID (primary key) field.

    • Leave the Target Foreign Key option unchecked.


      Note:

      The mapping is from the EMPLOYEE table, MANAGER_ID field to the EMP_ID field.


  9. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Creating Other One-to-one Mappings

The Advanced tutorial also includes a one-to-one mapping for the following attributes:

Create these mappings as shown in "Creating One-to-One Mappings Between Objects". Refer to Table B-13 for the correct relationships. Enable indirection for each of these mappings, as "Implementing Indirection in the Tutorial" indicates.

Implementing a One-to-Many Self-Relationship

Some object models require a class to reference another instance of the same class. In the advanced tutorial, a manager can have a collection of managed employees (see Figure B-1).

To map the managedEmployee attribute:
  1. Select the Employee's managedEmployees attribute in the Navigator pane, then click the One-to-Many Mapping button Text description of 1mmapbtn.gif follows.

    Text description of the illustration 1mmapbtn.gif

    on the mapping toolbar.

    The Editor pane displays the appropriate information for a one-to-many relationship to be specified.

  2. Use the Reference Descriptor drop-down list to choose Employee.

    Figure B-34 One-to-Many Mapping General Tab

    Text description of 1mmanemp.gif follows.

    Text description of the illustration 1mmanemp.gif

  3. Select the Use Indirection option, and choose ValueHolder. See "Implementing Indirection in the Tutorial".

  4. Click the Table Reference tab. Use the Table Reference drop-down list to choose the EMPLOYEE_EMPLOYEE table (previously created in "To map the manager attribute:").

    • Click the Add button on the Table Reference tab to add a foreign key relationship.

    • Set the Source Field (foreign key) to MANAGER_ID.

    • Set the Target Field (primary key) to EMP_ID.

      Figure B-35 One-to-Many Mapping Table Reference Tab

      Text description of 1mmantab.gif follows.

      Text description of the illustration 1mmantab.gif

  5. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Creating Other One-to-Many Mappings

The Advanced tutorial also includes a one-to-many mapping for the phoneNumbers attribute in the Employee descriptor. Create this mapping as shown in "Creating One-to-Many Mappings". Refer to Table B-13 for the correct relationship.

Enable indirection for this mapping, as indicated in "Implementing Indirection in the Tutorial".

Using Multiple Tables

In TopLink, it is possible to spread classes across two or more tables. In the advanced tutorial, the Employee class is stored in multiple tables: although most information is in the EMPLOYEE table, salary information is stored in the SALARY table.

To map the Employee class to multiple tables:
  1. Select the Employee descriptor in the Navigator pane.

  2. Click the Multi-Table Info tab in the Editor pane.

    If the Multi-Table info tab is not visible, right-click the Employee descriptor and choose Set Advanced Properties > Multi-Table Info from the pop-up menu.

  3. In the Additional Tables pane, click Add and add the SALARY table.

  4. In the Associated Via pane select Primary Key and in the Primary Key Table Reference pane, select Primary Keys Have Same Names.

    Figure B-36 Multi-Table Info Tab

    Text description of multitab.gif follows.

    Text description of the illustration multitab.gif

  5. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Implementing Object Type Mapping

In TopLink, you can match a fixed number of database values to Java objects through object type mappings. In the advanced tutorial, each employee's gender is stored as a single letter in the database field (M or F), but the value is the full name (Male or Female).

To map the gender attribute:
  1. Expand on the Employee descriptor in the Navigator pane.

  2. Select the gender attribute and click the Object-Type Mapping button Text description of obmapbtn.gif follows.

    Text description of the illustration obmapbtn.gif

    in the mapping toolbar.

    Figure B-37 Object-Type Mapping Tab

    Text description of otmap.gif follows.

    Text description of the illustration otmap.gif

  3. In the Database Field, select the GENDER field from the EMPLOYEE table.

  4. Select String as the Database Type, and String as the Object Type.

  5. Click Add and create the following database mappings:

    Database Value Object Value

    F

    Female

    M

    Male

  6. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Implementing an Aggregate Object

In TopLink, two objects are related by aggregation if there is a one-to-one relationship between the objects and all the attributes of the second object can be retrieved from the same table(s) as the owning object. In the advanced tutorial, the EmploymentPeriod is an aggregate descriptor, and the period attribute is an aggregate object.

To map an aggregate object:
  1. Select the EmploymentPeriod descriptor in the Navigator pane.

  2. Click the Aggregate Descriptor button Text description of agdesbtn.gif follows.

    Text description of the illustration agdesbtn.gif

    on the mapping toolbar. The descriptor's icon in the Navigator pane changes to an aggregate descriptor Text description of agdesicn.gif follows.

    Text description of the illustration agdesicn.gif

    .

  3. Map the startDate and EndDate attributes of the EmploymentPeriod as direct-to-field mappings.


    Note:

    The Database Field fields are disabled because the aggregate descriptor is not associated with a database table.


  4. Expand the Employee descriptor in the Navigator pane.

  5. Select the period attribute of the Employee descriptor.

  6. Click the Aggregate Mapping button Text description of agmapbtn.gif follows.

    Text description of the illustration agmapbtn.gif

    on the mapping toolbar.

    Figure B-38 Aggregate Mapping General Tab

    Text description of aggobj.gif follows.

    Text description of the illustration aggobj.gif

  7. Use the Reference Descriptor drop-down list to choose the EmploymentPeriod aggregate descriptor.

  8. Click the Fields tab.

    Figure B-39 Aggregate Mapping Fields Tab

    Text description of agmapfld.gif follows.

    Text description of the illustration agmapfld.gif

  9. Use the Fields drop-down list to map each field as follows:

    • endDate - END_DATE

    • startDate - START_DATE

  10. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Implementing a Direct Collection Mapping

Direct collection mappings store collections of Java objects that are not TopLink-enabled. In the advanced tutorial, the responsibilitiesList attribute is a direct collection.

To map a direct collection:
  1. Expand the Employee descriptor in the Navigator pane.

  2. Click the responsibilitiesList attribute of the Employee descriptor.

  3. Click the Direct Collect button Text description of dcmapbtn.gif follows.

    Text description of the illustration dcmapbtn.gif

    on the mapping toolbar.

  4. To specify where to place the strings in the direct collection, use the Target Table and Direct Field drop-down lists to select the DESCRIP field on the RESPONS databases table.

  5. Select the Use Indirection option and choose ValueHolder. See "Implementing Indirection in the Tutorial".

    Figure B-40 Direct Collection Mapping General Tab

    Text description of dctab.gif follows.

    Text description of the illustration dctab.gif

  6. Click the Table Reference tab, and add a new table reference by clicking the New button.

    • Create a reference named RESPONS_EMPLOYEE, with a source table of RESPONS and target table of EMPLOYEE and click OK.

    • In the Table Reference drop-down list, choose the RESPONS_EMPLOYEE.

    • Click the Add button on the Table Reference tab to add a foreign key relationship.

    • Set the Source Field (foreign key) to EMP_ID (from the RESPONS table).

    • Set the Target Field (primary key) to EMP_ID (from the EMPLOYEE table).

  7. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Implementing a Many-to-Many Mapping

Many-to-many mappings represent relationships between a collection of source objects and a collection of target objects. In the advanced tutorial, the projects attribute uses a many-to-many-mapping (for example, many employees can have many projects).

To map a many-to-many mapping:
  1. Expand the Employee descriptor in the Navigator pane.

  2. Click the projects attribute of the Employee descriptor.

  3. Click the Many-to-many Mapping button Text description of mmmapbtn.gif follows.

    Text description of the illustration mmmapbtn.gif

    on the mapping toolbar.

  4. Use the Reference Descriptor drop-down list to choose the BaseProject descriptor.

  5. Use the Relation Table drop-down list to choose the PROJ_EMP table (the class to map to).

  6. Ensure that the Use Indirection field is selected. See "Implementing Indirection in the Tutorial".

    Figure B-41 Many-to-Many Mapping General Tab

    Text description of mmmap.gif follows.

    Text description of the illustration mmmap.gif

  7. Click the Source Reference tab, and add a new reference by clicking the New button.

    • Create a new reference named PROJ_EMP_EMPLOYEE, with a source table of PROJE_EMP and target table of EMPLOYEE, and click OK.

    • In the Table Reference drop-down list, choose the PROJ_EMP_EMPLOYEE reference.

    • Click the Add button on the Source Reference tab to add a foreign key relationship.

    • Set the Foreign Key field to EMP_ID (from the PROJ_EMP table).

    • Set the Primary Key field to EMP_ID (from the EMPLOYEE table).

  8. Click the Target Reference tab, and add a new reference by clicking the New button.

    • In the Table Reference drop-down list, choose the PROJ_EMP_PROJECT reference.

    • Click the Add button on the Source Reference tab to add a foreign key relationship.

    • Set the Source Field field to PROJ_ID (from the PROJ_EMP table).

    • Set the Target Field field to PROJ_ID (from the PROJECT table).

  9. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Implementing Inheritance

Inheritance describes how a child class inherits the characteristics of its parent class. TopLink uses multiple implementations to support database inheritance.

In the advanced tutorial, the LargeProject and SmallProject classes inherit the characteristics of the BaseProject class. Use the following procedures to set the BaseProject descriptor to implement inheritance, then enable the two subclasses.

To implement inheritance in the BaseProject descriptor:
  1. Click the BaseProject descriptor in the Navigator pane.

  2. Click the Inheritance tab in the Editor pane.

    If the Inheritance tab is not visible, right-click the Project descriptor and choose Advanced Properties > Inheritance from the pop-up menu or Selected > Advanced Properties > Inheritance from the menu.

  3. Ensure that the Is Root Descriptor field is selected.

  4. Select the Use Class Indicator Field option, and use the drop-down list to choose PROJ_TYPE.

  5. Select the Use Class Indicator Dictionary field and choose a String type as the Indicator Type.

To implement inheritance in each subclass:
  1. Click the SmallProject descriptor in the Navigator pane.

  2. Click the Inheritance tab in the Editor pane.

    If the Inheritance tab is not visible, right-click the SmallProject descriptor and choose Advanced Properties > Inheritance from the pop-up menu or Selected > Advanced Properties > Inheritance from the menu.

  3. In the Parent Descriptor drop-down list, choose the BaseProject class.

  4. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Repeat this procedure for the LargeProject descriptor.

To complete the inheritance:
  1. Click the BaseProject descriptor in the Navigator pane.

  2. Click the Inheritance tab in the Editor pane.

  3. For each inherited descriptor:

    • Select the Include column.

    • Click Edit.

    • Enter an Indicator Value (S for SmallProject and L for LargeProject) for each child class.

      Figure B-42 Inheritance Tab

      Text description of inhertn.gif follows.

      Text description of the illustration inhertn.gif


      Note:

      To have the root class store instances of itself in the table, it must include a value-subclass pair for itself. This is not required for the advanced tutorial because Project is an abstract class.


Implementing a Transformation Mapping

Use transformation mappings for specialized translations between how a value is represented in Java and in the database. The method takes a database row as an argument and is called whenever an object is written to the database. The method returns the value from the object that should be written to the field.

In the advanced tutorial, the transformation method corresponds to a single argument method on the Employee class and extracts the values from the fields, placing them into the NormalHours array.

To map the normalHours attribute:
  1. Expand the Employee descriptor in the Navigator pane.

  2. Click the normalHours attribute of the Employee descriptor.

  3. Click the Transformation Mapping button Text description of trmapbtn.gif follows.

    Text description of the illustration trmapbtn.gif

    on the mapping toolbar.

  4. Use the Database Row -> Object Method drop-down list to select the bulidNormalHours method.

  5. Click the Add button to create the following Object->Field Methods:

  6. Click Save Text description of savebtn.gif follows.

    Text description of the illustration savebtn.gif

    on the toolbar or choose File > Save Project to save the project.

Mapping the Remaining Attributes

The remaining attributes for each descriptor are simple direct-to-field mappings. Use Table B-13 to map each attribute.

Completing the Tutorials

Generating Code

To use your project with the Foundation Library, you must either generate deployment XML files or export the project to Java source code.

In this tutorial, we will create a deployment XML file that can be read in at runtime. The code generator creates a single subclass that can be used instead of reading directly from the files.

To export to Java source code:
  1. Right-click the project in the Navigator pane and choose Export Project to Java Source from the pop-up menu. The Choose an Export File dialog box appears.

    You can also export the project by choosing File > Export to Java Source or Selected > Export to Java Source from the menu.

  2. Select a directory location and file name (.java) and click OK.

Congratulations! You have completed the Advanced Tutorial and are now familiar with TopLink's advanced topics and functions.

Completed versions of this tutorial (for various architectures and application servers) are included with the complete installation of TopLink in the following directory:

<ORACLE_HOME>\toplink\examples


Go to previous page Go to next page
Oracle
Copyright © 1997, 2003 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index