Oracle Application Server TopLink Mapping Workbench User's Guide 10g (9.0.4) Part Number B10316-01 |
|
This section contains the following tutorials that illustrate how to use Oracle Application Server TopLink Mapping Workbench.
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.
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.
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:
Employee
- Represents both full-time ACME employees and temporary contractors working on ACME projects. It includes the employees' personal information as well as references to their home addresses and phone numbers.
Address
- Represents the employee's home address. The class contains country, street, city, province, and postal code information.
PhoneNumber
- Contains the telephone number(s) for each employee and contractor (number, area code, and type information). The class also includes a reference to the employee who owns the phone number.
Figure B-1 illustrates the object model for this system.
Text description of the illustration intrmod.gif
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. |
Column Name | Column Type | Details |
---|---|---|
EMP_ID |
NUMERIC(15) |
Primary key |
F_NAME |
VARCHAR(40) |
|
L_NAME |
VARCHAR(40) |
|
ADDRESS_ID |
NUMERIC(15) |
|
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) |
|
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.
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.
The splash screen appears, followed by the OracleAS TopLink Mapping Workbench window.
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.
Employee.mwp
.
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.
Employee
project in the Navigator pane.
<ORACLE_HOME>
\toplink\examples\foundation\
threetier\stage
directory and click OK.
Note:
If the |
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save to save the project.
The Employee
model uses three classes:
Employee
class has a name attribute and privately owned PhoneNumber
and Address
relationships.
PhoneNumber
class has attributes describing the phone number information and a relationship that describes the owner of the PhoneNumber.
Address
class has attributes describing the employee's mailing address.
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.
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); }
You must generate an OracleAS TopLink descriptor for each Java class in the project.
Employee
project.
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.
examples.sessions.threetier.model
package. Click the plus sign (
Text description of the illustration plus.gif
) to expand that package (or double-click the name to expand the package).Address
class and click the
Text description of the illustration arrow.gif
button. OracleAS TopLink copies theAddress
class to the Selected Classes pane.
Employee
and PhoneNumber
classes in that package. (Or, highlight both classes using Shift+click or Ctrl+click as necessary, and click
Text description of the illustration arrow.gif
once to import all the remaining classes.)
Note: If an error occurs, check that the given classes are included in the class path and that JDK has been installed correctly. |
Text description of the illustration mwemp1.gif
Figure B-12 identifies the following user-interface elements:
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
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. |
Text description of the illustration loginbtn.gif
or choose Selected > Log In to Database from the menu. The database icon changes toIf 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.
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.
Use this procedure to create the database tables from the OracleAS TopLink Mapping Workbench.
Use this procedure to create table definitions using the OracleAS TopLink Mapping Workbench. Later, you can create the actual tables on the database.
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.
ADDRESS
for the table name, and click OK.
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. |
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
Repeat this procedure for the EMPLOYEE
and PHONE
tables.
After defining the tables in OracleAS TopLink Mapping Workbench, you can automatically create the tables on 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:
Text description of the illustration logotbtn.gif
or choose Selected > Log Out from the menu.
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. |
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. |
Text description of the illustration loginbtn.gif
or choose Selected > Login from the menu.
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.
Text description of the illustration importdb.gif
Figure B-15 calls out the following user-interface elements:
ADDRESS
table in the Available Tables pane and then click the
Text description of the illustration arrow.gif
button. TheADDRESS
table moves to the Selected Tables pane.
EMPLOYEE
and PHONE
tables.
Text description of the illustration logotbtn.gif
or choose Selected > Log Out of Database from the menu.
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
Continue with "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.
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.
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.
Use this procedure to associate the Java classes with database tables.
Address
descriptor from the Navigator pane.
Address
table.
Text description of the illustration descinfo.gif
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.
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.
ADDRESS
database table.
ADDRESS_ID
column is selected as a Primary Key.
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
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.
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.
Text description of the illustration addtable.gif
. The New Table dialog box appears.SEQUENCE
. Leave Catalog and Schema blank, unless required by your specific database.
SEQ_NAME
field as the primary key.
The Address
class does not reference any other classes. Its attributes map directly to database fields as a direct-to-field mapping.
Address
descriptor in the Navigator pane.
city
attribute.
Text description of the illustration dtfmpbtn.gif
on the mapping toolbar. The Direct-to-Field mapping tab appears in the Editor pane.
CITY
field.
ADDRESS
table.
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
The Address
and Employee
classes use nonnative sequencing for primary keys.
ACME_ADDRESS
and use the drop lists to choose the Table and Field, as in Figure B-22.
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
Employee
class. Use ACME_EMPLOYEE
as the Name, and choose EMPLOYEE
and EMP_ID
from the Table and Field drop-down lists, respectively.
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.
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.
firstName
and lastName
attributes as a direct-to-field mapping to the F_NAME
and L_NAME
fields, respectively.
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.
Text description of the illustration 11mapfig.gif
address
attribute in the Navigator pane, then click the One-to-one Mapping button
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.
Address
as the reference descriptor.
This allows the Address
object to be created, updated, or deleted automatically when the Employee owning it is changed.
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.
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.
EMPLOYEE_ADDRESS
from the Table Reference drop-down list.
Text description of the illustration savebtn.gif
or choose File > Save from the menu.
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.
Text description of the illustration 1mmapfig.gif
In this tutorial, the Employee project requires:
phoneNumbers
attribute of the Employee
class to the PhoneNumber
class
owner
attribute of the PhoneNumber
class back to the Employee
class
Employee
class in the Navigator pane.
phoneNumbers
attribute.
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.
PhoneNumber
.
PHONE_EMPLOYEE
with a source table of PHONE
and a target table of EMPLOYEE
and click OK.
PHONE_EMPLOYEE
.
EMP_ID
and the Target (primary key) field to EMP_ID
.
After mapping the Employee
descriptor, use this procedure to map the one-to-one back reference:
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").
EMPLOYEE
as the Reference Descriptor.
Phone
descriptor as direct-to-field mappings (refer to "Implementing Direct-to-Field Mappings").
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.
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.
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.
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.
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.
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();
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.
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.
Text description of the illustration uow.gif
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.
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.
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();
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.
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();
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:
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:
EmploymentPeriod
- Defines the contract term for contractors and the hire date for ACME employees. Each Employee
class has an EmploymentPeriod
.
ResponsibilityList
- Each Employee
has a collection of text that describes the employee's job.
BaseProject
- Maintains information about a particular project and the people working on it. The Project
class contains two subclasses: LargeProject
and SmallProject
. Each Employee
can be involved in more than one project.
TeamLeader
- Each Project
can have a team leader (the Employee
responsible for the project.
Manager
- Each Employee
may have a manager and a collection of managed employees.
Figure B-1 illustrates the object model for the advanced tutorial.
Text description of the illustration advmodel.gif
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.
Column Name | Column Type | Details |
---|---|---|
EMP_ID |
NUMERIC(15) |
Primary key |
SALARY |
NUMERIC(10) |
|
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) |
|
Column Name | Column Type | Details |
---|---|---|
EMP_ID |
NUMERIC(15) |
Primary key |
AREA_CODE |
CHAR(3) |
|
P_NUMBER |
CHAR(7) |
|
TYPE |
VARCHAR(15) |
Primary key |
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) |
|
Column Name | Column Type | Details |
---|---|---|
PROJ_ID |
NUMERIC(15) |
Primary key |
BUDGET |
NUMERIC(10,2) |
|
MILESTONE |
TIMESTAMP |
|
Column name | Column type | Details |
---|---|---|
EMP_ID |
NUMERIC(15) |
Primary key |
DESCRIP |
VARCHAR(200) |
|
Column Name | Column Type | Details |
---|---|---|
EMP_ID |
NUMERIC(15) |
Primary key |
PROJ_ID |
NUMERIC(15) |
Primary key |
examples.session.threetier.model
package. See "Setting the Project's Class Path".
examples.session.threetier.model
package, and generate a TopLink descriptor for each Java class as "Generating the Class Definitions" describes:
Table B-13 shows how the classes relate to the database tables.
Select one of the following methods to add database information:
Refer to Table B-5 through Table B-12 for complete database information.
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. |
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. |
Address
class in the Navigator pane and click the Descriptor Info tab in the Editor pane.
You must associate the class with a table before using the Automap tool.
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.
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.
To prepare your object model for indirection, you must alter the application slightly:
ValueHolderInterface
. This interface is located in the oracle.toplink.indirection
package and allows for indirection to be used.
get
methods for these variables to extract the value from the value holder.
set
methods for these variables to insert the value into the value holder.
You can implement indirection using direct access or method access.
get
and set
methods that provide access to the value holders.
get
and set
methods are not required.
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.
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.
After modifying the code, update the OracleAS TopLink Mapping Workbench descriptors to use indirection.
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.
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).
manager
attribute in the Navigator pane, then click the One-to-One Mapping button
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.
Employee
as the reference descriptor.
EMPLOYEE_EMPLOYEE
(created in step 5 from the Table Reference drop-down list.
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
The Advanced tutorial also includes a one-to-one mapping for the following attributes:
address
attribute in the Employee
descriptor
owner
attribute in the PhoneNumber
descriptor
teamLeader
attribute in the BaseProject
descriptor
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.
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).
managedEmployees
attribute in the Navigator pane, then click the One-to-Many Mapping button
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.
Employee
.
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
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".
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.
Employee
descriptor in the Navigator 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.
SALARY
table.
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
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).
Employee
descriptor in the Navigator pane.
gender
attribute and click the Object-Type Mapping button
Text description of the illustration obmapbtn.gif
in the mapping toolbar.
Database Value | Object Value |
---|---|
|
|
|
|
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
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.
EmploymentPeriod
descriptor in the Navigator pane.
Text description of the illustration agdesbtn.gif
on the mapping toolbar. The descriptor's icon in the Navigator pane changes to an aggregate descriptorText description of the illustration agdesicn.gif
.
startDate
and EndDate
attributes of the EmploymentPeriod
as direct-to-field mappings.
period
attribute of the Employee
descriptor.
Text description of the illustration agmapbtn.gif
on the mapping toolbar.EmploymentPeriod
aggregate descriptor.
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
Direct collection mappings store collections of Java objects that are not TopLink-enabled. In the advanced tutorial, the responsibilitiesList
attribute is a direct collection.
Employee
descriptor in the Navigator pane.
responsibilitiesList
attribute of the Employee
descriptor.
Text description of the illustration dcmapbtn.gif
on the mapping toolbar.
RESPONS_EMPLOYEE
, with a source table of RESPONS
and target table of EMPLOYEE
and click OK.
RESPONS_EMPLOYEE
.
EMP_ID
(from the RESPONS table).
EMP_ID
(from the EMPLOYEE table).
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
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).
Employee
descriptor in the Navigator pane.
projects
attribute of the Employee
descriptor.
Text description of the illustration mmmapbtn.gif
on the mapping toolbar.
Project
descriptor.
PROJ_EMP
table (the class to map to).
PROJ_EMP_EMPLOYEE
, with a source table of PROJE_EMP
and target table of EMPLOYEE,
and click OK.
PROJ_EMP_EMPLOYEE
reference.
EMP_ID
(from the PROJ_EMP table).
EMP_ID
(from the EMPLOYEE table).
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
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.
BaseProject
descriptor in the Navigator 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.
PROJ_TYPE
.
SmallProject
descriptor in the Navigator 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.
BaseProject
class.
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.
BaseProject
descriptor in the Navigator pane.
SmallProject
and L for LargeProject
) for each child class.
Text description of the illustration inhertn.gif
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.
Employee
descriptor in the Navigator pane.
normalHours
attribute of the Employee
descriptor.
Text description of the illustration trmapbtn.gif
on the mapping toolbar.
Text description of the illustration savebtn.gif
on the toolbar or choose File > Save Project to save the project.
The remaining attributes for each descriptor are simple direct-to-field mappings. Use Table B-13 to map each attribute.
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.
You can also export the project by choosing File > Export to Java Source or Selected > Export to Java Source from the menu.
.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
|
![]() Copyright © 1997, 2003 Oracle Corporation. All Rights Reserved. |
|