Skip Headers

Oracle9iAS TopLink Tutorials
Release 2 (9.0.3)

Part Number B10062-01
Go To Documentation Library
Home
Go To Solution Area
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

1
Introductory Tutorial

In the introductory tutorial, you will create mappings from a simple database application using 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 will manage the employee database at the ACME Leisure Company. The system tracks each employee's name, address, and phone number.

The system use these classes:

The following figure illustrates the object model for this system.

Figure 1-1 The 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. To use this tutorial, create these tables in your database application.


Note:

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


Table 1-1 The EMPLOYEE Table
Column name Column type Details

EMP_ID

NUMERIC(15)

Primary key

NAME

VARCHAR(40)

ADDRESS_ID

NUMERIC(15)

Table 1-2 The 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 1-3 The PHONENUMBER 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

TopLink Mapping Workbench stores project information in the .mwp file and associated folders. You should always start a Mapping Workbench project in a new folder.

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

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

    Figure 1-2 Mapping Workbench

    Text description of mw.gif follows.

    Text description of the illustration mw.gif

  2. Click on the New Project button Create New Project button. in the toolbar or select File > New Project from the menu. The Create a New Project window appears.

    Figure 1-3 Create New Project

    Text description of createnw.gif follows.

    Text description of the illustration createnw.gif

  3. From the Create New Project window:

    • In the Database Name field, type INTRO_TUTORIAL_DB.

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

  4. Click OK. The Save As screen appears.

    Figure 1-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.

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

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

    Figure 1-5 Mapping Workbench

    Text description of mwnew.gif follows.

    Text description of the illustration mwnew.gif

  8. Click on Save Save Project button. in the toolbar or select File > Save to save the project.


    Note:

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


Setting the Project's Classpath

Each TopLink project uses a classpath - a set of directories, .jar files, and .zip files - when importing Java classes and defining object types.

  1. In the Mapping Workbench, highlight the Employee project in the Project Tree pane.

  2. In the Properties pane on the right-hand side of the TopLink Mapping Workbench screen, click on the General tab.

    Figure 1-6 General Tab

    Text description of general.gif follows.

    Text description of the illustration general.gif

  3. Click on Add Entry. The Add Entry screen appears.

    Figure 1-7 Add Entry

    Text description of empclsen.gif follows.

    Text description of the illustration empclsen.gif

  4. Browse to the <INSTALL_DIR>\tour\lib\tl_demo.jar directory and click on Add.

    Figure 1-8 General Tab with Classpath Information

    Text description of generlzi.gif follows.

    Text description of the illustration generlzi.gif

  5. Click on Save Save Project button. in the toolbar or select 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 oracle.toplink.demos.employee.domain package) for this tutorial, as described in "Generating the Class Definitions".

The following table shows how the classes relate to the database tables.

Table 1-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:

It is good programming practice to supply each of the class members in TopLink enabled classes with accessor methods. For this tutorial, the get and set methods for each of the attributes are provided. The Employee class should have an addPhoneNumber() method to allow a new PhoneNumber to store a reference to its parent.


Example 1-1 Accessor Method Example

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 a TopLink descriptor for each Java class in the project.

To create descriptors from the class definition file:
  1. From the TopLink Mapping Workbench screen, click on the Employee project.

  2. Click on the Add/Update Class button Add/Update Class button. or select Selected > Add/Update Classes from the menu. The Select Classes screen appears.

    Figure 1-9 Select Classes

    Text description of selectcl.gif follows.

    Text description of the illustration selectcl.gif

  3. Locate the oracle.toplink.tutorials.intro package. Click on the plus sign ( Plus icon. ) to expand that package (or double-click on the name to expand the package).

    Figure 1-10 Demo Classes

    Text description of selclsex.gif follows.

    Text description of the illustration selclsex.gif

  4. Highlight the Address class, and click the Arrow. button or double-click on the class.

    TopLink copies the Address class to the Selected Classes pane.

    Figure 1-11 Selected Class

    Text description of selctadd.gif follows.

    Text description of the illustration selctadd.gif

  5. Repeat step Step 4 for Employee and PhoneNumber classes in that package. (Or, highlight both classes using Shift+click or Ctrl+click as necessary, and click the Arrow. button once to import all of the remaining classes.)

  6. Click OK to import the classes. TopLink creates a descriptor for each class and an unmapped mapping for each attribute.

    The descriptors and their attributes appear in the Project Tree pane on TopLink Mapping Workbench screen.


    Note:

    If an error occurs during this operation, check that the given classes are included in the CLASSPATH and that JDK has been installed correctly.


    Figure 1-12 Mapping Workbench with Employee Project

    Text description of mwclass.gif follows.

    Text description of the illustration mwclass.gif

    User-interface elements called out in Figure 1-12:

    1. Package

    2. Class/descriptors

  7. Save your changes. Click on the Save Project button Save Project button. or select File > Save from the menu.

Logging into the Database

You can enter database table information directly from 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.

  1. Click on the INTRO_TUTORIAL_DB database object in the Project Tree pane. The Database Properties pane appears on the right-hand side of the TopLink Mapping Workbench screen.

    Figure 1-13 Database Properties

    Text description of dblogin.gif follows.

    Text description of the illustration dblogin.gif

  2. Click on Add to create a new database login. Contact your database administrator for the necessary database login information.

  3. In the toolbar, click the Login to Database button Login button. or select Selected > Login from the menu. The database icon changes to  Database login icon. .


    Note:

    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 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 Oracle9iAS TopLink Troubleshooting Guide for details.

Creating Tables

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

Creating Tables Using the Mapping Workbench

Use this procedure to create the database tables from the 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 use the Mapping Workbench to create table definitions. Later you can create the actual tables on the database.

To create the tables:
  1. Click on the database in the Project Tree pane and click on the Add a New Table to the Database button Add New Table button. or right-click on the database in the project tree 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 on the Fields tab in the Properties pane.

  4. Click on the Add button 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).


    Figure 1-14 Database Fields Tab

    Text description of fldaddr.gif follows.

    Text description of the illustration fldaddr.gif

  5. Save your changes. Click on the Save Project button Save Project button. or select 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 TopLink Mapping Workbench, you can automatically create the tables on the database.

To create tables on the database:
  1. Right-click on one of the database tables in the tree pane, and select Create on Database > All Tables from the pop-up menu.


    Note:

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


    If the Confirm Replace window 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)

    or

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

    The system displays a message indicating that the three tables were created.

  2. Click OK to close the dialog and return to the TopLink Mapping Workbench screen.

  3. In the toolbar, click the Logout of Database button Logout of Database button. or select Selected > Log Out from the menu.

  4. Save your changes. Click on the Save Project button Save Project button. or select File > Save from the menu.

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


Tip:

TopLink Mapping Workbench can generate Data Definition Language (DDL) creation scripts that can be used to create tables on the desired database. See the Oracle9iAS TopLink Mapping Workbench Reference Guide for more information. If the table creation fails, there may 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. The DDL may not be compatible with some databases, so you may have to edit the generated DDL and execute the DDL manually.


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 Mapping Workbench.


Caution:

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


To import tables from the database:
  1. Click the Login to Database button Login button. or select Selected > Login from the menu.

  2. Click on the database in the Project Tree pane and click on the Add/Update Existing Tables from Database button Add/Update Table from Database button. or right-click on the database choose Add/Update Existing Tables From Database from the pop-up menu.

    The Import tables from database window appears.

    Figure 1-15 Import Tables from Database

    Text description of importdb.gif follows.

    Text description of the illustration importdb.gif

    User-interface elements called out in Figure 1-15:

    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 on the Get Table Names button to display all tables in the database.


    Note:

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


  4. Click on the ADDRESS table in the Available Tables pane and then click the Arrow. button. The ADDRESS table moves to the Selected Tables pane.

  5. Repeat step 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, choose a table in the Project Tree pane and click on the Fields tab in the Properties pane.

  8. In the toolbar, click the Logout of Database button Logout of Database button. or select Selected > Log Out from the menu.

  9. Save your changes. Click on the Save Project button Save Project button. or select 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, 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 the mapping the descriptors, you can access the database from a Java application.

Mappings

The 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. TopLink Mapping Workbench stores the descriptors in XML files in the Descriptor directory. At run time, TopLink creates instances of the Descriptor class for each of the descriptor files and stores them in a database session.

Mapping Classes to Tables

To map Java classes to a table:
  1. Click on the Address descriptor from the Project Tree pane.

  2. Click on the Descriptor Info tab of the Properties pane.

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

    Figure 1-16 Descriptor Info Tab

    Text description of descinfo.gif follows.

    Text description of the illustration descinfo.gif


    Note:

    A warning message appears indicating that the primary key fields are unmapped. This will be 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 on the Save Project button Save Project button. or select 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. 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 is inserted into a database.

To specify the primary key:
  1. In the Project Tree pane, click the ADDRESS database table.

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

    Figure 1-17 Database Table Field Tab

    Text description of addridpk.gif follows.

    Text description of the illustration addridpk.gif

  3. Repeat steps 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 on the Save Project button Save Project button. or select 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. Click on the database in the Project Tree pane and log into the database by clicking the Login button Login button. or by right-clicking on the Database in the Project Tree and choosing Login from the pop-up menu.

  2. Click on the Database in the Project Tree pane and click the Add Table button Add New Table button. . The New Table dialog box appears.

    Figure 1-18 New Table

    Text description of newtble.gif follows.

    Text description of the illustration newtble.gif

  3. Create a table named SEQUENCE.

  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 on the Database in the project tree and choosing Log Out from the pop-up menu.

  7. Click on the Project in the Project Tree pane.

  8. Click the project's Sequencing tab in the Properties pane.

    Figure 1-20 Sequencing Tab

    Text description of sequence.gif follows.

    Text description of the illustration sequence.gif

  9. Select Use Custom Sequence Table and use the drop lists to choose the Name, Seq. Name Field, and Seq. Counter Field, as shown in Figure 1-20.

  10. Save your changes. Click on the Save Project button Save Project button. or select 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 Project Tree pane.

  2. Click on the city attribute.

  3. Click the Direct-to-field mapping button Direct-to-field Mapping button. in the mapping toolbar. The Direct-to-Field mapping tab appears in the Properties pane.

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

    Figure 1-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

    • 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 on the Save Project button Save Project button. or select File > Save from the menu.

Setting the Sequence Name

The Address and Employee classes use non-native 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 TopLink's SchemaManager. Refer to the Oracle9iAS TopLink Mapping Workbench Reference Guide for more information.


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

  2. Click the Descriptor Info in the Properties 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 1-22.

    Figure 1-22 Descriptor Info Tab

    Text description of seqname.gif follows.

    Text description of the illustration seqname.gif

  5. Save your changes. Click on the Save Project button Save Project button. or select 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 on the Save Project button Save Project button. or select 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 name attribute as direct-to-field to the NAME field.

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

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

Figure 1-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. Click on the Employee's address attribute in the Project Tree pane, then click the One-to-one Mapping button One-to-one Mapping button. in the mapping toolbar.

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

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

    Text description of chseref.gif follows.

    Text description of the illustration chseref.gif

  2. Select the Use Indirection check box.

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

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

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 TopLink knows how to search for a referenced object, as illustrated in Figure 1-23.

  1. Click the Table Reference tab.

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

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

    Select the On Database option if you want to create the reference on the database when you create the tables. TopLink doesn't 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. Select EMPLOYEE_ADDRESS from the Table Reference drop-down list.

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

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

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

    • Leave the Target Foreign Key option unchecked.

      Figure 1-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 on the Save Project button Save Project button. or select 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 1-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 Project tree pane.

  2. Select the phoneNumbers attribute.

  3. Click the One-to-many Mapping button One-to-many Mapping button. in the mapping toolbar. The Properties pane changes to allow the appropriate information for a one-to-many relationship to be specified.

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

    Figure 1-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 on New.

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

    • In the Table Reference drop-down list, select 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 1-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 on the Save Project button Save Project button. or select File > Save from the menu.


    Note:

    Leave the remaining attributes of the Employee descriptor as unmapped. They will be used 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").


    Note:

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


  2. Select EMPLOYEE as the Reference Descriptor.

  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 on the attribute and select Remove from the pop-up menu.

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

Setting up Database Sessions

A database session in TopLink for Java 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.

A test class has been included with TopLink 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 code fragment in the following Example 1-2, "Logging in and Creating a Project Example Code" illustrates this approach.

Example 1-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:\\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 TopLink Mapping Workbench to create database tables. 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 examples illustrates how to create the EMPLOYEE table after having logged in to 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 1-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 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 either be 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 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 illustrated in Figure 1-29.

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 1-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 using 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 "Logging into a Database", Example 1-3 and uses the session created there.

Example 1-4 Unit of Work Example

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 change to the database using the commit() method.

Example 1-5 Session Example

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 tutorial explained the basic steps required to create a Java project that accesses a relational database through TopLink. The main concepts explained include:


Go to previous page Go to next page
Oracle
Copyright © 2002 Oracle Corporation.

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