Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

310
SG24-5471-00 International Technical Support Organization www.redbooks.ibm.com IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Ueli Wahli, Tobias Himstedt, Sean Lee, Amir Razmara

Transcript of Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Page 1: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SG24-5471-00

International Technical Support Organization

www.redbooks.ibm.com

IBM WebSphere and VisualAge for JavaDatabase Integration with DB2,Oracle, and SQL Server

Ueli Wahli, Tobias Himstedt, Sean Lee, Amir Razmara

Page 2: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o
Page 3: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM WebSphere and VisualAge for JavaDatabase Integration with DB2,Oracle, and SQL Server

September 1999

SG24-5471-00

International Technical Support Organization

Page 4: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

© Copyright International Business Machines Corporation 1999. All rights reserved.Note to U.S Government Users – Documentation related to restricted rights – Use, duplication or disclosure issubject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.

First Edition (September 1999)

This edition applies to

• IBM WebSphere Application Server Version 2.0.2• IBM WebSphere Studio Version 3.0 beta 2• VisualAge for Java Version 2 with Rollup 2 and Enterprise Update• DB2 Universal Database Version 5.2• Oracle Version 8• Microsoft SQL Server Version 7

for use with the Windows NT Operating System, Service Pack 4.

Sample Code on the Internet:

Comments may be addressed to:IBM Corporation, International Technical Support OrganizationDept. QXXE Building 80-E2650 Harry RoadSan Jose, California 95120-6099

When you send information to IBM, you grant IBM a non-exclusive right to use or distribute theinformation in any way it believes appropriate without incurring any obligation to you.

The sample code for this redbook is available as 5471samp.zip file on the ITSO home page on theInternet:

ftp://www.redbooks.ibm.com/redbooks/SG245471/

Download the sample code and read Chapter 3, “ITSO Sample Applications” on page 15.

Before using this information and the product it supports, be sure to read the general information inAppendix B, “Special Notices” on page 269.

Take Note!

Page 5: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Contents

Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xixThe Team That Wrote This Redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxComments Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi

Part 1. Introduction to IBM WebSphere and VisualAge for Java .1

Chapter 1. HTTP Server and WebSphere Application Server . . . . 3Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3IBM HTTP Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

IBM WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5WebSphere Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5WebSphere Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6WebSphere Configuration for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Starting and Stopping WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Chapter 2. VisualAge for Java Enterprise Version 2 . . . . . . . . . . . . 9VisualAge for Java Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10VisualAge for Java Configuration for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . 10VisualAge for Java Configuration for WebSphere . . . . . . . . . . . . . . . . . . . . 10WebSphere in VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Default Directories for Servlets and JSP files . . . . . . . . . . . . . . . . . . . . 11Compiled JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Running Servlets in VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter 3. ITSO Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . 15Sample Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Repository Export Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

© Copyright IBM Corp. 1999 iii

Page 6: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Part 2. Database Setup and JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19

Chapter 4. Relational Database Installation and Setup . . . . . . . . 21DB2 UDB Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

DB2 UDB Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22DB2 UDB Table Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Loading the Table Data Into DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26DB2 JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Oracle 8 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Oracle Database Setup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Oracle Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Importing the Table Data into Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Oracle JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

SQL Server Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33SQL Server Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33SQL Server Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Importing the Table Data into SQL Server. . . . . . . . . . . . . . . . . . . . . . . 35SQL Server JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38ODBC Data Source Setup for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Chapter 5. Java Database Connectivity. . . . . . . . . . . . . . . . . . . . . . . 43DB2 UDB JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

DB2 Application Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44DB2 Network Driver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

Oracle JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Oracle Thin Client Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Oracle OCI Driver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

SQL Server JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Configuring VisualAge for Java for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . 48Configuring WebSphere for JDBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Part 3. Database Programming Examples . . . . . . . . . . . . . . . . . . . . .51

Chapter 6. JDBC Programming Examples . . . . . . . . . . . . . . . . . . . . 53Simple JDBC Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53DB2 Universal Database JDBC Code Example . . . . . . . . . . . . . . . . . . . . . . 56Oracle JDBC Code Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57SQL Server JDBC Code Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Running Applications with JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Testing the JDBC Applications in VisualAge for Java. . . . . . . . . . . . . . 60Running the JDBC Applications in the Operating System . . . . . . . . . . 60

Simple JDBC Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

iv IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 7: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Testing the Servlet in VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . 63Running the Servlet in WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Chapter 7. IBM Connection Manager . . . . . . . . . . . . . . . . . . . . . . . . . 65Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Connection Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67IBM Connection Manager and Pure JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . 69IBM Connection Manager Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Using the IBM Connection Manager. . . . . . . . . . . . . . . . . . . . . . . . . . . . 70HTML File for Accessing the Servlets. . . . . . . . . . . . . . . . . . . . . . . . . . . 71Running the Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72DbaseConnMgr Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Microsoft SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Chapter 8. Data Access Beans: VisualAge for Java . . . . . . . . . . . . 81Loading the Data Access Bean Feature. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Data Access Beans and the Standard SQL Classes . . . . . . . . . . . . . . . . . . . 82

DatabaseConnection and java.sql.Connection . . . . . . . . . . . . . . . . . . . . 83Statement Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85ResultSet Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Building a Servlet using Data Access Beans. . . . . . . . . . . . . . . . . . . . . . . . . 86Sample Data Access Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86Creating a Servlet Visually using Data Access Beans . . . . . . . . . . . . . . 86

Using the Connection Manager and Data Access Beans . . . . . . . . . . . . . . . 98Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99Form Parameter Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Form Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Employee Retrieval. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Employee Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Testing the Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

Deploying Servlets to WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Chapter 9. Persistence Builder: VisualAge for Java . . . . . . . . . . 109What is Persistence?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110Using Databases to Provide Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . 110Persistence Builder Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110Vendor Specific Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Persistence Builder Example: Employees in Department . . . . . . . . . . . . . 112

Import the Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112Generate and Validate the Object Model . . . . . . . . . . . . . . . . . . . . . . . 115Inspect the Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

v

Page 8: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Generate the Java Code for the Object Model . . . . . . . . . . . . . . . . . . . 118Generate the Java Code for the Service Classes. . . . . . . . . . . . . . . . . . 119Build the Servlet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Changing the Datastore Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127Deploying a Servlet to WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

Chapter 10. Enterprise JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . 131Enterprise JavaBeans from a Bird’s-Eye Perspective . . . . . . . . . . . . . . . . 132A Closer Look . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Developing a Container Managed Persistence Entity Bean . . . . . . . . . . . 133

Setup of VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Create a Department Enterprise Bean . . . . . . . . . . . . . . . . . . . . . . . . . 135Add the Properties and Methods to the Bean . . . . . . . . . . . . . . . . . . . . 137Map the Bean to the Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Generate the Code and Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Deploy the Enterprise Bean to WebSphere. . . . . . . . . . . . . . . . . . . . . . . . . 149Access the Department Bean from a Servlet. . . . . . . . . . . . . . . . . . . . . . . . 153

Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Perform Task Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Retrieve a Department Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Create or Find a Department Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Update the Department Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Test the Servlet in VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . 158Test the Servlet in WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

Access the Department Bean from an Application . . . . . . . . . . . . . . . . . . . 160Create the GUI Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160Create the Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Test the Applet or Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Developing a Bean Managed Persistence Entity Bean. . . . . . . . . . . . . . . . 164Create an Employee Enterprise Bean with the SmartGuide. . . . . . . . 164Add Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Provide the Employee Bean with Persistence Functionality . . . . . . . . 166The EmployeeStorage Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Testing the Employee Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174Access the Employee Bean from a Servlet . . . . . . . . . . . . . . . . . . . . . . 174Deployment of the Employee Bean to WebSphere . . . . . . . . . . . . . . . . 177

Chapter 11. WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179WebSphere Studio Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Installation and Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Project Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Create an SQL Statement and Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

vi IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 9: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Create the Servlet and JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188Project View after the Database Wizard . . . . . . . . . . . . . . . . . . . . . . . . 192

Publish the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194Publishing Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194Assembly Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196Publishing Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

Testing the Generated Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Enhanced Insert Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

Create an SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198Create a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200Viewing the Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200Determine all Available Department Numbers . . . . . . . . . . . . . . . . . . 201Invoke the Servlet from a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202Save the Modified HTML Page as a JSP. . . . . . . . . . . . . . . . . . . . . . . . 207Modify the Generated Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207Test the JSP and the Servlet in WebSphere . . . . . . . . . . . . . . . . . . . . . 208

Debugging the Servlets in VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . 210Hints and Tips for WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

Synchronization between Development and Publishing View. . . . . . . 211Checkout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211Publishing Warnings About Old Class Files. . . . . . . . . . . . . . . . . . . . . 211Mismatch between Servlet and Servlet Configuration. . . . . . . . . . . . . 211

Project View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

Chapter 12. WebSphere User Profile . . . . . . . . . . . . . . . . . . . . . . . . . 213Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

Enable Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214Database Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Connection Manager Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

User Profile Create, Update and Retrieve. . . . . . . . . . . . . . . . . . . . . . . . . . 218Create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219Retrieve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

UserProfile Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220Classes and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220Output Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228XML, HTML, and JSP Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Testing the User Profile Sample in VisualAge for Java. . . . . . . . . . . . 235Running the User Profile Sample in WebSphere . . . . . . . . . . . . . . . . . 236

Chapter 13. WebSphere Security and the LDAP Directory . . . . 237Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

vii

Page 10: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Access Control Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238Realms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

Setup and Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Chapter 14. Using SQLJ to Access a Database . . . . . . . . . . . . . . . . 247What is SQLJ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248SQLJ and VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248SQLJ Translators, Input, and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249Updating Serialized Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249DB2 Resources for SQLJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250Using the SQLJ Translator with DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250Employees in Department Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251Bean with SQLJ Code Before Translation . . . . . . . . . . . . . . . . . . . . . . 252SQLJ Code After Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

Deployment of an SQLJ Servlet to WebSphere . . . . . . . . . . . . . . . . . . . . . 258SQLJ Servlet Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261

Appendix A. Odds and Ends. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Different Mapping of SQL Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264Correct Deployment of Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . 266Data Access Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266WebSphere Studio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

Appendix B. Special Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

Appendix C. Related Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . 273International Technical Support Organization Publications . . . . . . . . . . . 274Redbooks on CD-ROMs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275Other Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

How to Get ITSO Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277IBM Redbook Fax Order Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278

List of Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

ITSO Redbook Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

viii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 11: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figures

1. WebSphere Administrator Login Panel . . . . . . . . . . . . . . . . . . . . . . . . 62. WebSphere Administration Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73. Services Panel: Starting and Stopping WebSphere . . . . . . . . . . . . . . . 84. Add Feature to VisualAge for Java Environment . . . . . . . . . . . . . . . 105. Feature Selection Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116. Class Path Setup for the WebSphere Test Environment . . . . . . . . . . 137. Sample Console Output from SERunner . . . . . . . . . . . . . . . . . . . . . . 148. Creating a New Database using the Control Center . . . . . . . . . . . . . 229. Create Database SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2310. Add User to a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2411. DB2 Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2512. DB2 Sample Data Extract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2613. Creating a New User for Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2814. Assigning a Role to an Oracle User . . . . . . . . . . . . . . . . . . . . . . . . . . . 2815. Oracle Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2916. Oracle Table Creation Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3017. Import Data For The Employee Table . . . . . . . . . . . . . . . . . . . . . . . . 3118. Oracle Sample Data Extract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3219. Create a New Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3320. SQL Server Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3521. Import Data for Department Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 3622. Choose a Destination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3723. Select the Destination Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3724. Importing Data Was Successful. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3825. ODBC Data Source Administrator . . . . . . . . . . . . . . . . . . . . . . . . . . . 3926. Create New Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3927. Create New Data Source to SQL Server . . . . . . . . . . . . . . . . . . . . . . . 4028. Create New Data Source to SQL Server (Database Setup) . . . . . . . . 4129. Category 2 JDBC Driver, Vendor Specific Bridge . . . . . . . . . . . . . . . 4430. Category 3 JDBC Driver, Generic Network Protocol . . . . . . . . . . . . . 4531. Editing VisualAge for Java’s Class Path. . . . . . . . . . . . . . . . . . . . . . . 4832. JDBC Drivers in WebSphere Class Path . . . . . . . . . . . . . . . . . . . . . . 4933. Simple Class for JDBC Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5434. JDBC Example Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5535. DB2 UDB JDBC Code Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5636. Oracle JDBC Code Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5737. ODBC DSN Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5838. ODBC Data Source Administrator . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

© Copyright IBM Corp. 1999 ix

Page 12: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

39. SQL Server JDBC Example Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5940. Simple Servlet doGet Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6241. Simple Servlet Output in a Web Browser . . . . . . . . . . . . . . . . . . . . . . 6442. Interaction Flow Between the Connection Manager and a Servlet. . 6643. Connection Management on WebSphere . . . . . . . . . . . . . . . . . . . . . . 6744. Connection Pool Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6845. HTML for the Connection Manager Servlet Examples . . . . . . . . . . . 7146. Launching a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7247. Exporting a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7348. DbaseConnMgr Class Declaration. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7349. DbaseConnMgr init Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7450. DbaseConnMgr initConnection Method . . . . . . . . . . . . . . . . . . . . . . . 7451. DbaseConnMgr getConnection Method. . . . . . . . . . . . . . . . . . . . . . . . 7452. DbaseConnMgr releaseConnection Method . . . . . . . . . . . . . . . . . . . . 7553. DBaseConnMgr executeSelect Method . . . . . . . . . . . . . . . . . . . . . . . . 7554. DBaseConnMgr outputInfo Method . . . . . . . . . . . . . . . . . . . . . . . . . . 7555. doGet Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7656. UdbConnMgr Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7757. UdbConnMgr getDriver Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7758. UdbConnMgr getPoolName Method . . . . . . . . . . . . . . . . . . . . . . . . . . 7759. UdbConnMgr getUrl Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7860. Connection Manager Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7861. OracleConnMgr Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . 7962. SqlSrvConnMgr Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . 7963. Data Access Beans Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8364. Internal Connection Management by DatabaseConnection . . . . . . . 8465. External Connection Management by IBM ConnectionManager . . . 8466. Select Statement Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8567. Servlet User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8768. The Servlet Palette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8869. Servlet with Data Access Bean and Select Bean . . . . . . . . . . . . . . . . 8870. UdbEmpInDept Connection Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . 8971. Connection Alias Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9072. UdbEmpInDept SQL Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9073. Creating New SQL Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9174. Selecting a Table for the Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9175. Setting Query Condition(s) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9276. Selecting Columns to Include for a Query . . . . . . . . . . . . . . . . . . . . . 9377. SQL Query Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9478. Resulting SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9579. UDB Servlet Using Data Access Beans: Visual Composition . . . . . . 9680. Tailored Method with Short Columns Names . . . . . . . . . . . . . . . . . . 9781. Output Result of the Servlet in a Web Browser . . . . . . . . . . . . . . . . . 97

x IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 13: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

82. EmployeeServlet Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . 9883. EmployeeServlet init Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9984. EmployeeServlet getParameter Method . . . . . . . . . . . . . . . . . . . . . . 10085. EmployeeServlet doGet and doPost Methods . . . . . . . . . . . . . . . . . . 10186. EmployeeServlet performTask Method. . . . . . . . . . . . . . . . . . . . . . . 10187. EmployeeServlet getEmployee Method (I) . . . . . . . . . . . . . . . . . . . . 10288. EmployeeServlet getEmployee Method (II) . . . . . . . . . . . . . . . . . . . 10289. getEmployee Method (III) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10390. EmployeeServlet getEmployee Method (IV) . . . . . . . . . . . . . . . . . . . 10391. Output of the getEmployee Method . . . . . . . . . . . . . . . . . . . . . . . . . 10492. EmployeeServlet getEmployee Method (V). . . . . . . . . . . . . . . . . . . . 10493. EmployeeServlet getEmployee Method (VI) . . . . . . . . . . . . . . . . . . . 10494. EmployeeServlet updateEmployee Method (I) . . . . . . . . . . . . . . . . . 10595. EmployeeServlet updateEmployee Method (II) . . . . . . . . . . . . . . . . 10596. EmployeeServlet updateEmployee Method (III). . . . . . . . . . . . . . . . 10597. EmployeeServlet updateEmployee Method (IV). . . . . . . . . . . . . . . . 10698. EmployeeServlet updateEmployee Method (IV). . . . . . . . . . . . . . . . 10699. Properties for the Employee Servlet . . . . . . . . . . . . . . . . . . . . . . . . . 107100. Importing a Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112101. Import Table Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113102. Schema Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114103. Schema Column Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114104. Model Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115105. Attribute Editor: Marking the Value Required Field. . . . . . . . . . . . 116106. Map Browser with a Broken Table Map . . . . . . . . . . . . . . . . . . . . . . 117107. Model Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117108. Generation Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118109. Generation Options (Bean Properties) . . . . . . . . . . . . . . . . . . . . . . . 119110. Schema Generation Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120111. Database Connection Information. . . . . . . . . . . . . . . . . . . . . . . . . . . 121112. HTML Output Page of a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122113. Visual Composition Editor with Persistence Builder Palette . . . . . 123114. Composition Editor with Connections. . . . . . . . . . . . . . . . . . . . . . . . 124115. Column Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125116. Servlet Test Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126117. Establishing Connections to Multiple Database Vendors . . . . . . . . 127118. Exporting the Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128119. WebSphere Application Server: Java Engine Setup . . . . . . . . . . . . 129120. Available Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134121. EJB Development Pane: Adding an EJB Group. . . . . . . . . . . . . . . . 135122. EJB SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136123. Adding a Field. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137124. Switching to the Fields Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

xi

Page 14: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

125. Add Methods to the Remote Interface. . . . . . . . . . . . . . . . . . . . . . . . 139126. Marking Properties Container Managed . . . . . . . . . . . . . . . . . . . . . 140127. Connection Information for the Schema Import. . . . . . . . . . . . . . . . 140128. Select the Table to Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141129. Schema Browser after Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141130. Specifying the Datastore Map for the Enterprise Bean . . . . . . . . . . 142131. Map Browser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142132. The Property Map Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143133. EJB Server Configuration Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . 144134. EJB Server Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144135. EJS Console Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145136. Test Client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146137. The Home Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146138. Parameter Specification for the DepartmentKey . . . . . . . . . . . . . . . 147139. Test Client Presenting the Remote Interface . . . . . . . . . . . . . . . . . . 148140. WebSphere General EJB Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . 150141. WebSphere Container EJB Settings . . . . . . . . . . . . . . . . . . . . . . . . . 151142. EJB Jar File Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151143. Redeployment Warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152144. DepartmentEJBServlet Class Declaration . . . . . . . . . . . . . . . . . . . . 154145. DepartmentEJBServlet performTask Method . . . . . . . . . . . . . . . . . 154146. DepartmentEJBServlet init Method . . . . . . . . . . . . . . . . . . . . . . . . . 155147. DepartmentEJbServlet getDepartment Method . . . . . . . . . . . . . . . 156148. DepartmentEJBServlet createOrFindDepartment Method . . . . . . 157149. DepartmentEJBServlet updateDepartment Method . . . . . . . . . . . . 158150. DepartmentEJBServlet in a Browser . . . . . . . . . . . . . . . . . . . . . . . . 159151. Department Panel with All Connections . . . . . . . . . . . . . . . . . . . . . 160152. DepartmentPanel createOrFind Method . . . . . . . . . . . . . . . . . . . . . 162153. Department Panel Displaying the Department Bean . . . . . . . . . . . 163154. Adding a BMP Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164155. Properties in the Workspace View. . . . . . . . . . . . . . . . . . . . . . . . . . . 165156. EmployeeBean ejbFindByPrimaryKey Method . . . . . . . . . . . . . . . . 167157. EmployeeBean ejbStore Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167158. EmployeeBean Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168159. EmployeeStorage Class Declaration . . . . . . . . . . . . . . . . . . . . . . . . . 169160. Initialize the Select Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170161. EmployeeBean ejbStore Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171162. Find an Employee. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172163. Update the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173164. Retrieve and Display the Employee Bean. . . . . . . . . . . . . . . . . . . . . 175165. Set the Properties of the Employee Bean . . . . . . . . . . . . . . . . . . . . . 176166. EmployeeEJBServlet Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176167. Create New Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

xii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 15: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

168. Specify Project Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182169. WebSphere Studio Project Window . . . . . . . . . . . . . . . . . . . . . . . . . . 182170. WebSphere Studio Tool Bar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183171. Specify a Name for the SQL Statement . . . . . . . . . . . . . . . . . . . . . . 183172. Specify the Connection Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 184173. Select Tables from the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185174. Specify the Join. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185175. Specify the Columns to Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186176. Specify the Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187177. Completed SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187178. Select the SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188179. Select the Generated Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189180. Specify Input Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189181. Specify the Fields for the Result Page. . . . . . . . . . . . . . . . . . . . . . . . 190182. Specify to Use the Bean in a Session. . . . . . . . . . . . . . . . . . . . . . . . . 191183. Provide Package Name and Class Name Prefix . . . . . . . . . . . . . . . . 191184. Finish the Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192185. Project after Servlet Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192186. Specify Publishing Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194187. Publishing Server Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195188. Publishing Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196189. Select Preview from the Context Menu. . . . . . . . . . . . . . . . . . . . . . . 197190. Generated HTML Input Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197191. Generated HTML Output Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198192. Creating an Insert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199193. Select the Input Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199194. Generated SQL Insert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 200195. Insert a New Employee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201196. Select the DEPNO Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202197. WebSphere Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203198. Specify the Servlet to be Invoked . . . . . . . . . . . . . . . . . . . . . . . . . . . 203199. Specify Bean Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204200. Resulting Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205201. Selecting the Loop Property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206202. Generated Code for Dynamic Item Values . . . . . . . . . . . . . . . . . . . . 207203. Enhanced Insert Servlet Input Page with Combobox . . . . . . . . . . . 209204. Complete Project View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212205. Enabling User Profile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215206. UserProfile Database Setup for DB2. . . . . . . . . . . . . . . . . . . . . . . . . 216207. UserProfile Database Setup for Oracle . . . . . . . . . . . . . . . . . . . . . . . 216208. UserProfile Database Setup for SQL Server. . . . . . . . . . . . . . . . . . . 217209. UserProfile’s Connection Pool Selection . . . . . . . . . . . . . . . . . . . . . . 217210. itsowasdb.userprofile Class Listing. . . . . . . . . . . . . . . . . . . . . . . . . . 220

xiii

Page 16: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

211. UserProfileCartServlet Methods Listing . . . . . . . . . . . . . . . . . . . . . 221212. UserProfileCartServlet Class Declaration . . . . . . . . . . . . . . . . . . . . 221213. UserProfileCartServlet addUserShoppingCart Method . . . . . . . . . 222214. UserProfileCartServlet.createUserProfile . . . . . . . . . . . . . . . . . . . . 222215. UserProfileCartServlet doGet Method . . . . . . . . . . . . . . . . . . . . . . . 222216. UserProfileCartServlet doPost Method. . . . . . . . . . . . . . . . . . . . . . . 223217. UserProfileCartServlet getParameter Method . . . . . . . . . . . . . . . . . 223218. UserProfileCartServlet itemCreateToOutputPage Method. . . . . . . 224219. UserProfileCartServlet performTask Method . . . . . . . . . . . . . . . . . 225220. UserProfileCartServlet processLogin Method . . . . . . . . . . . . . . . . . 226221. UserProfileCartServlet retrieveUserProfile Method . . . . . . . . . . . . 227222. UserProfileCartServlet userCreateToOutputPage Method . . . . . . . 227223. UserProfile Login Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228224. UserProfile UserCreate Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228225. UserProfile Default OutputPage After User Registration . . . . . . . . 229226. UserProfile ItemCreate Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229227. UserProfile Default Output Page After Item Creation . . . . . . . . . . 230228. UserProfileCartServlet.Servlet Control File. . . . . . . . . . . . . . . . . . . 231229. UserProfileLogin.html File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231230. UserProfileCreate.jsp File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232231. UserProfileCartOutputPage.jsp File . . . . . . . . . . . . . . . . . . . . . . . . . 233232. ItemInfoInputPage.jsp File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234233. UserProfileCartErrorPage.jsp File . . . . . . . . . . . . . . . . . . . . . . . . . . 234234. User Profiles Properties File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235235. Relationships Between Realm, ACL, and Resource . . . . . . . . . . . . . 239236. WebSphere Administration Setup for Directory Management . . . . 241237. WebSphere Access Control List Main Panel. . . . . . . . . . . . . . . . . . . 242238. Adding a New Access Control List . . . . . . . . . . . . . . . . . . . . . . . . . . 242239. Add Permission to ACL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243240. WebSphere Access Control List Main Panel with New ACL . . . . . . 244241. WebSphere Resources Security Setup. . . . . . . . . . . . . . . . . . . . . . . . 244242. Protect a Resource using Directory Service through ACL . . . . . . . . 245243. Resource Panel after Adding a Resource to be Protected. . . . . . . . . 245244. SQLJ Example Servlet (SqljServ.java) . . . . . . . . . . . . . . . . . . . . . . . 251245. SQLJ Example Servlet Bean (SqljServBean.sqlj) Part 1 . . . . . . . . . 252246. SQLJ Example Servlet Bean (SqljServBean.sqlj) Part 2 . . . . . . . . . 253247. SQLJ Code after Translation: Iterator Class Definition . . . . . . . . . 255248. SQLJ Code after Translation: Simple Select Statement . . . . . . . . . 256249. SQLJ Code after Translation: Select Without Result Set . . . . . . . . 257250. WebSphere Application Server: Java Engine Setup . . . . . . . . . . . . 258251. Output of SQLJ Servlet Employees in Department Example . . . . . 259252. Default Mapping for the Employee Table in DB2 . . . . . . . . . . . . . . 264253. Default Mapping for the Employee Table in Oracle. . . . . . . . . . . . . 265

xiv IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 17: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

254. Default Mapping for the Employee in ODBC/SqlServer . . . . . . . . . 265255. WebSphere Studio Database Wizard . . . . . . . . . . . . . . . . . . . . . . . . 267

xv

Page 18: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

xvi IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 19: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Tables

1. Directories and Files with Sample Code . . . . . . . . . . . . . . . . . . . . . . . . . 162. Models and Packages in the Repository Samples. . . . . . . . . . . . . . . . . . 173. Properties of the Employee Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

© Copyright IBM Corp. 1999 xvii

Page 20: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

xviii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 21: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Preface

With the move of Java applications to a servlet runtime environment on aWeb server the access of relational databases on the Web server becomes oneof the most important topics.

IBM WebSphere is a set of software products that help customers developand manage high-performance Web sites to ease the transition from simpleWeb publishing to advanced e-business applications.

VisualAge for Java Enterprise is the premier Java integrated developmentenvironment that helps customers connect their Java applications to theirenterprise data. VisualAge for Java provides an integrated WebSphere TestEnvironment that makes development and deployment of servlets toWebSphere fast and easy.

In this redbook we describe many ways of how relational database systemscan be integrated with the VisualAge for Java development environment andthe WebSphere execution environment.

First, we describe the installation of the underlying base products IBMWebSphere and VisualAge for Java. Next, we describe the installation andsetup of the database systems and JDBC drivers for the three relationaldatabase management systems DB2 Universal Database, Oracle, andMicrosoft SQL Server. Finally, we provide small programming examples forJDBC, data access beans, the Persistence Builder, Enterprise JavaBeans,WebSphere Studio, User Profiles, Security and Directory Services, and SQLJ.

This redbook is especially suited for Java application designers that areimplementing servlets with relational database access.

© Copyright IBM Corp. 1999 xix

Page 22: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The Team That Wrote This RedbookThis redbook was produced by a team of specialists from around the worldworking at the International Technical Support Organization San JoseCenter.

Ueli Wahli is a Consultant AD Specialist at the IBM International TechnicalSupport Organization in San Jose, California. Before joining the ITSO 14years ago, Ueli worked in technical support at IBM Switzerland. He writesextensively and teaches IBM classes worldwide on application development,object technology, VisualAge products, data dictionaries, and librarymanagement. Ueli holds a degree in Mathematics from the Swiss FederalInstitute of Technology. His e-mail address is [email protected].

Tobias Himstedt is a Senior Consultant working for SerCon GmbH, an IBMGlobal Service Company in Mainz, Germany. Tobias holds a diploma inComputer Science from the University of Hildesheim, Germany. He isco-author of a book about Python, a useful scripting language. Before joiningSerCon he worked for GMD, the German National Research Center forInformation Technology. There, he was mainly involved in a Europeanresearch project about electronic commerce. His areas of expertise includeInternet, client/server, object-oriented, and component technologies (e-mail:[email protected]).

Sean Lee is an IT Specialist currently engaged in customer consulting inNew York. He is a DB2 Technical Specialist representing the DB2development lab in San Jose, California. Sean has 2 years of experience inInformation Technologies and holds a degree in Computer Science from theState University of New York in Binghamton. His areas of expertise includeSystem/390 database management and connectivity. You can contact Sean [email protected].

Amir Razmara is an IT Specialist in Canada. He has 6 years of experiencein the software development field. He holds a degree in Computer Sciencefrom the York University in Toronto, Canada. His areas of expertise includeobject-oriented analysis and design, database servers, client/server andinternet solutions for e-business. His e-mail address is [email protected].

xx IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 23: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Thanks to the following people for their invaluable contributions to thisproject:

Joaquin PiconInternational Technical Support Organization, San Jose Center

Moncrief Rowe-AndersonIBM Santa Teresa Lab (DB2 JDBC SQLJ)

Virinder BatraIBM Raleigh

Comments WelcomeYour comments are important to us!

We want our redbooks to be as helpful as possible. Please send us yourcomments about this or other redbooks in one of the following ways:

❑ Fax the evaluation form found in “ITSO Redbook Evaluation” on page 285to the fax number shown on the form.

❑ Use the online evaluation form found at http://www.redbooks.ibm.com

❑ Send your comments in an internet note to [email protected]

xxi

Page 24: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

xxii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 25: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Part 1 Introduction toIBM WebSphereand VisualAgefor Java

In this part we briefly discuss the installation of the two products,IBM WebSphere and VisualAge for Java Enterprise.

© Copyright IBM Corp. 1999 1

Page 26: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

2 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 27: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

1 HTTP Server andWebSphereApplication ServerIn this chapter we describe the IBM HTTP Server and the IBM WebSphereApplication Server. The functionality of these products will be brieflydiscussed, including a few hints and tips on how to set them up to run yourservlets inside and outside of the VisualAge for Java environment.

EnvironmentThe examples in this book were developed in the following environment:

❑ PCs with Pentium II 450 MHZ processors and 128 MB RAM

❑ MS Windows NT 4.0 service pack 4

❑ Both Netscape Navigator 4.5 and Microsoft Internet Explorer 4.0 wereused interchangeably through the test and usage of different components.

© Copyright IBM Corp. 1999 3

Page 28: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM HTTP ServerIBM HTTP Server is a Web server which shares its base code with theApache Server, with additional enhancements such as the Secure SocketLayer (SSL).

InstallationIBM HTTP Server Version 1.3.3.1 was used to run the sample code providedin this book.

Be sure to consider the following during the installation:

❑ Make sure there is a user ID dedicated to be used only by the HTTPserver.

❑ The user ID must be a member of the Administrator group.

Once you have created the user ID proceed with the installation. As you stepthrough the installation pages enter the user ID created prior to theinstallation into the Information for Service Setup panel.

ConfigurationTo configure the HTTP server you should use the httpd.doc file located under<drive>:\Program Files\IBM HTTP Server\conf. You can customize the HTTPServer using the tags in httpd.conf file. Here is a description on some of thosetags:

DocumentRoot: The directory where the HTTP Server looks for the HTMLfiles. The default set value is <drive>:/Program Files/IBM HTTP Server/htdocs.

Alias: To create a specific location for your project you can take advantage ofthe Alias tag. This tag can be set to point to any directory where you wish toplace your HTML and JSP files. If you want to access files which reside in alocation other than the DocumentRoot directory, you can use an Alias to dothis. For example, to be able to access test.html from a c:\itsowww directory,set Alias /itso/ "C:/itsowww/" in the httpd.conf file. This way, to access thetest.html file from the browser the following URL should be used:

http://<server name>/itso/test.html

ServerRoot: The directory where the server's configuration, error, and logfiles are kept.

ServerName: If you observe any problems with the IBM HTTP Server itmight help to explicitly set the server name to your host name.

4 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 29: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM WebSphere Application ServerThe WebSphere Application Server implements a servlet engine thatfunctions as a plug-in to extend the capabilities of a number of Web servers.WebSphere is an application server that enables the “write once, useanywhere” concept for servlets.

WebSphere can work with number of different Web servers, such as:

❑ IBM HTTP Server ❑ Apache Server 1.3.x ❑ Lotus Domino 5.0 ❑ Lotus Domino Go Webserver ❑ Netscape Enterprise Server ❑ Netscape FastTrack Server ❑ Microsoft Internet Information Server

All of the samples provided in this book have used the IBM HTTP Server astheir Web server.

With a properly coded URL, client requests to a Web server are passed on tothe Application Server. The Application Server, in turn, passes the clientrequest information to a Java servlet, which acts on the request informationand prepares a response that is sent back to the client through theApplication Server and the Web server.

A Java servlet is basically an ordinary piece of Java code with addedcapabilities provided by APIs in the javax.servlet and javax.servlet.httppackages. These packages are standard Java extensions available fromJavaSoft for JDK 1.1 and built-in to JDK 1.2. The request/response model isused by general Web browser and server interactions over the Internet, andit applies to servlet behavior as well. Because HTTP is a stateless protocol,one request/response knows nothing about another request/response, evenfrom the same Web browser, unless additional session state features areadded.

WebSphere InstallationThe WebSphere Application Server Version 2.02 was used to run the samplecode provided in this book.

One thing to consider prior to installation is to make sure you are using aspecific IP address instead of an IP address provided through a DHCP server(we did experience problems with a DHCP address).

Chapter 1. HTTP Server and WebSphere Application Server 5

Page 30: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The installation process for WebSphere Application Server is fairly simple.The only thing you need to know is the Web server that is used withWebSphere. It is a good idea to install the Web server prior to installingWebSphere. Also make sure you select the right Web server to work withWebSphere, because there is no easy way to change this after theinstallation.

WebSphere ConfigurationTo configure different components of WebSphere you use the administrationapplet of WebSphere. To gain access on your browser input the followingURL: http://<server-name>:9527 or http://<ip-address>:9527. This starts theapplet and displays the main administrator login panel (Figure 1).

Figure 1. WebSphere Administrator Login Panel

From the administration panel you configure different components ofWebSphere (Figure 2).

6 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 31: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 2. WebSphere Administration Panel

Servlet and Java Class Files LocationThe servlet and Java class files should reside under:

<drive>:\WebSphere\AppServer\servlets\<package name (if any)> or <drive>:\WebSphere\AppServer\classes\<package-name>.

Keep in mind that the classes placed under the servlets directory can bereplaced at any time without the need to restart WebSphere. On the otherhand, the classes placed under the classes directory do require WebSphere tobe restarted when they are replaced. Therefore, the classes directory is theproper place to store any packages that will most likely not change, while theservlets directory is the best place during development and testing.

Servlets are addressed with the URL:

http://<server-name>/servlet/packagename.ClassName

WebSphere Configuration for JDBCTo run a servlet with JDBC in WebSphere, we have to make the JDBCdrivers available. See “Configuring WebSphere for JDBC” on page 49 fordetailed instructions.

Chapter 1. HTTP Server and WebSphere Application Server 7

Page 32: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Starting and Stopping WebSphereWhen using the IBM HTTP server it is not necessary to start WebSphereexplicitly. This is done automatically when the HTTP Server is started.

To stop WebSphere use the Control Panel->Services (Figure 3) and stop theWebSphere Servlet Service. Next, stop the IBM HTTP Server. To restart, juststart the IBM HTTP Server again and verify that the WebSphere ServletService is started as well.

Figure 3. Services Panel: Starting and Stopping WebSphere

8 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 33: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

2 VisualAge for JavaEnterprise Version 2Because VisualAge for Java Version 2 contains some very nice tools todevelop, debug, and run servlets and Enterprise JavaBeans in a testenvironment, VisualAge for Java was used to develop the samples.

In this chapter we briefly describe how to install and configure VisualAge forJava to work properly with the IBM WebSphere Test Environment.

© Copyright IBM Corp. 1999 9

Page 34: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

VisualAge for Java InstallationThe installation consists of three steps:

1. Install VisualAge for Java version 2.0 GA release, reboot, start Visual Agefor Java, and exit.

2. Install fixpack Rollup 2 by unzipping the file rollup2_vaj20_win.zip to theVisualAge for Java directory (c:\IBMVAJava), start VisualAge for Java tocomplete the installation, and exit.

3. Install the Enterprise Update, start VisualAge for Java, and exit.

During the installation VisualAge for Java asks for the directory forHTML files; the default path is <drive>:\www\html. This is the locationwhere the IBM WebSphere Test Environment looks for the HTML files.

VisualAge for Java Configuration for JDBCTo run Java programs with JDBC in VisualAge for Java, we have to make theJDBC drivers available. See “Configuring VisualAge for Java for JDBC” onpage 48 for detailed instructions.

VisualAge for Java Configuration for WebSphereOnce the installation is complete, you should add the IBM WebSphere TestEnvironment feature to the Workbench by selecting Workbench -> File ->Quick Start (Figure 4).

Figure 4. Add Feature to VisualAge for Java Environment

10 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 35: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Select Feature->Add Feature and select IBM WebSphere Test Environment1.1 (Figure 5).

Figure 5. Feature Selection Panel

If the feature has already been added it will not be listed. Adding the featurewill allow you to run servlets within the VisualAge for Java environment.

WebSphere in VisualAge for JavaIn this section we describe the necessary steps involved in setting up andrunning servlets inside VisualAge for Java.

Default Directories for Servlets and JSP filesThe HTML and JSP files should reside under:

<drive>:\www\html (refer to “VisualAge for Java Installation” on page 10)

The XML servlet configuration files (.servlet) should reside under:

<drive>:\IBMVJava\ide\project_resources\<project name>\<[package name]>

Chapter 2. VisualAge for Java Enterprise Version 2 11

Page 36: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Compiled JSPsWhen the JSP file is accessed through a servlet it is translated into a Javafile and its class is executed in the VisualAge for Java environment. The Javaversion of the JSP file can be found in the JSP Page Compile Generated Codeproject in the VisualAge for Java Workbench.

Running Servlets in VisualAge for JavaThere are a couple of steps you have to take to run your Websphereapplication. From the Workbench select the com.ibm.servlet package in theIBM WebSphere Test Environment project. Execute the SERunner class tostart the servlet runtime environment. Depending on the processing power ofyour machine this will take between 20 to 120 seconds to get started.

Before running SERunner make sure the project in which the servlet code isresiding is included in the class path of SERunner (Figure 6).

One safe option is to select all the projects and add them to the class path ofthe SERunner class.

To run JSPs, the JSP Page Compile Generated Code project must also beadded to the class path. This project does not exist originally; it is createdwhen the first JSP is compiled. Only then can the project be added to theclass path of the SERunner class.

12 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 37: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 6. Class Path Setup for the WebSphere Test Environment

When the WebSphere test environment is up and running you can launchyour servlets by selecting the servlet class and Tools -> Servlet Launcher ->Launch from the context menu. If the SERunner is not running, this processwill launch the SERunner. After SERunner is launched, a series of messagesis displayed in the Console window of VisualAge for Java. At some point amessage “ServerProcess: Server started” gets logged. Despite what themessage indicates, the server does some further processing before it is fully

Chapter 2. VisualAge for Java Enterprise Version 2 13

Page 38: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

operational. Figure 7 shows the final message in the Console window thatindicate the server is truly up and running.

Figure 7. Sample Console Output from SERunner

Checking if server is already started on port: 8080***Starting WebSphere Test Environment***ServerProcess: Start servicesServiceManager: Load service adminservice . . . .Servlet reloading is disabledServiceManager: Autostarting servletserviceServiceManager: Autostarting httpserviceServerProcess: Server started. . . .servletservice: Load (update): endpoint.main.port=80ServiceParameters: servletservice: Load (update): endpoint.main.port=80

14 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 39: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

3 ITSO SampleApplicationsThe sample code developed for this book is available as a ZIP file on theInternet:

ftp://www.redbooks.ibm.com/redbooks/SG245471/

The 5471samp.zip file expands into a directory structure containing all thesample code:

\WasDbBk\Code <=== sample files for book chapters\WasDbBk\Code\Repository <=== VisualAge for Java export files (.dat)

© Copyright IBM Corp. 1999 15

Page 40: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Sample CodeTable 1 describes the sample code subdirectory structure and the filescontained in those subdirectories.

Table 1. Directories and Files with Sample Code

Subdirectory Files Description

Main directory: \WasDbBk\Code

DBase xxx.ddl Database definition DDL for DB2,Oracle, and SQL Server

xxx.icx, xxx.csv Sample table data load files

Repository xxx.dat VisualAge for Java repository exportfile

itso\wasdb\..pkg xxx.class, xxx.java VisualAge for Java exported classes,matching the package structure

deployableEJBs xxx.jar VisualAge for Java jar files fordeployment of EJBs to WebSphere

Html xxx.html HTML, JSP, and servlet XML files

Studio xxx.war WebSphere Studio archive file

xxx.java, .html,.jsp, .servlet, .sql

WebSphere Studio generated files

16 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 41: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Repository Export FilesThe repository subdirectory (\WasDbBk\code\Repository) contains one file:

5426samp.dat (contains project ITSO SG24 5471)

Table 2 describes the samples that we developed and the repository packageswhere the code is stored.

Table 2. Models and Packages in the Repository Samples

To load the packages into the repository, use the import function of VisualAgefor Java. You can import the whole projects or just individual packages. Afterimporting you have to load the packages into the Workbench, either into yourown project or by using the ITSO SG24 5471 project.

Package Description

itso.wasdb.jdbc JDBC example and servlet example

itso.wasdb.connmgr Connection manager example

itso.wasdb.accessbean Data access bean example

itso.wasdb.connaccess Data access bean with connection manager

itso.wasdb.persist.metadata Persistence Builder model, schema, map

itso.wasdb.persist Persistence Builder domain classes

itso.wasdb.persist.Services Persistence Builder service classes

itso.wasdb.persist.gui Persistence Builder GUI application

itso.wasdb.ejb Enterprise JavaBeans

itso.wasdb.ejb.client Enterprise JavaBeans client example

itso.wasdb.ejb.servlet Enterprise JavaBeans servlet example

itso.wasdb.studio WebSphere Studio example

itso.wasdb.userprofile WebSphere user profile example

itso.wasdb.sqlj DB2 SQLJ example

ITSO_EJBsEJBReserved Enterprise JavaBeans control information

Chapter 3. ITSO Sample Applications 17

Page 42: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

18 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 43: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Part 2 Database Setupand JDBC

In this part we discuss the installation and setup required for all of therelational database products and the setup required to create a JDBCconnection to your database.

In our project we used three different relational database managementsystems, together with the WebSphere Application Server, WebSphereStudio, and VisualAge for Java

❑ DB2 UDB Version 5.2

❑ Oracle 8i, Version 8.0.4

❑ Microsoft SQL Server, version 7.0

© Copyright IBM Corp. 1999 19

Page 44: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

20 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 45: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

4 Relational DatabaseInstallation andSetupIn this chapter we describe the installation and setup of the relationaldatabase products used for the examples throughout this book. For thepurpose of the samples provided, all of the databases do share the same nameand table formats. Because the scripts used to create these databases wereslightly different, all three scripts are posted here.

To standardize the data structures accessed in each of the database products,we created a simple sample database called ITSOWDB to run queriesagainst. We created a schema under the ID ITSO. Therefore all of the tablenames used are ITSO.<TABLENAME>. The sample data definition language(DDL) or SQL file for every database is listed under the correspondinginstallation section.

© Copyright IBM Corp. 1999 21

Page 46: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2 UDB InstallationWe installed DB2 Universal Database for Windows NT Version 5.2. To keepthe version current, UDB fixpack WR09074, also known as fixpack 6, wasinstalled.

To use the SQLJ functionality, you must install fixpack 8 (see Chapter 14,“Using SQLJ to Access a Database” on page 247).

DB2 UDB Database SetupAfter DB2 is installed, you need to create the ITSOWDB database. You caneither use a GUI with the DB2 Control Center or use a DB2 commandwindow.

If you are using the Control Center, you select Systems -> [ComputerName] ->Instances -> DB2 -> Databases. Open the context menu (right click) andselect Create->New (Figure 8).

Figure 8. Creating a New Database using the Control Center

A SmartGuide prompts you for the database name (Figure 9). For thepurpose of our sample code, you do not have to use the other pages of theSmartGuide dialog. Enter the name and click on Done.

22 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 47: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 9. Create Database SmartGuide

If you are using a DB2 Command Window run the command:

db2 create database itsowdb

If you want to find out more about the create database options, enter:

db2 ? create database

This command lists all of the options available for the particular DB2command.

User IDBy convention we create all tables under the ITSO user ID (with thepassword itso). Because of this you need to add the ITSO user ID to thedatabase user list. Make sure that the user ID ITSO is already created in theWindows NT operating system.

The simplest way to to add the user ID to the database is through the ControlCenter. Select the ITSOWDB database and open User and Group Objects. Inthe context menu (right mouse click) select DB Users and select Add. Fromthe Add User panel select the ITSO user ID and give it all of the Authorities.Then click on Apply and then on Close (Figure 10).

Chapter 4. Relational Database Installation and Setup 23

Page 48: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 10. Add User to a Database

DB2 UDB Table CreationWhen the database is created, the next step is to create the tables in thedatabase. Figure 11 shows the itsowdb.ddl file file used to create the tables.To execute this file, open a DB2 Command Window and run the command:

db2 -tvf itsowdb.ddl

Use the proper directory (c:\WasDbBk\dbase\db2) for the script file.

Two tables are created:

❑ Department

❑ Employee

These tables definitions are similar to the tables of the DB2 SAMPLEdatabase. We decided not to use the SAMPLE database, so that we can havethe same database and tables in all three database systems.

24 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 49: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 11. DB2 Table Creation

CONNECT TO itsowdb;

DROP TABLE ITSO.EMPLOYEE;DROP TABLE ITSO.DEPARTMENT;

----------------- DDL Statements for table ITSO.DEPARTMENT

CREATE TABLE ITSO.DEPARTMENT ( DEPTNO CHAR(3) NOT NULL , DEPTNAME VARCHAR(29) NOT NULL , MGRNO CHAR(6) , ADMRDEPT CHAR(3) NOT NULL , LOCATION CHAR(16) );

ALTER TABLE ITSO.DEPARTMENTADD PRIMARY KEY (DEPTNO);

----------------- DDL Statements for table ITSO.EMPLOYEE

CREATE TABLE ITSOWDB.ITSO.EMPLOYEE ( EMPNO CHAR(6) NOT NULL , FIRSTNME VARCHAR(12) NOT NULL , MIDINIT CHAR(1) NOT NULL , LASTNAME VARCHAR(15) NOT NULL , WORKDEPT CHAR(3) , PHONENO CHAR(4) , HIREDATE DATE , JOB CHAR(8) , EDLEVEL SMALLINT NOT NULL , SEX CHAR(1) , BIRTHDATE DATE , SALARY DECIMAL(9,2) , BONUS DECIMAL(9,2) , COMM DECIMAL(9,2) );

ALTER TABLE ITSO.EMPLOYEEADD PRIMARY KEY (EMPNO);

----------------- DDL Statement for foreign key relationship

ALTER TABLE ITSO.EMPLOYEE ADD FOREIGN KEY (WORKDEPT) REFERENCES ITSO.DEPARTMENT (DEPTNO) ON DELETE RESTRICT;

----------------- Load sample data

LOAD FROM DEPARTMENT.CSV OF DEL INSERT INTO ITSO.DEPARTMENT;LOAD FROM EMPLOYEE.CSV OF DEL INSERT INTO ITSO.EMPLOYEE;SET CONSTRAINTS FOR ITSO.EMPLOYEE IMMEDIATE CHECKED;

CONNECT RESET;

Chapter 4. Relational Database Installation and Setup 25

Page 50: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Loading the Table Data Into DB2The load statements at the bottom of Figure 11 load the sample data into thetables from a data file that uses one line of comma-delimited data for eachrow of the tables.

An extract of the sample data (.csv files) is shown in Figure 12.

Figure 12. DB2 Sample Data Extract

DB2 JDBC DriversThe DB2 JDBC drivers are in the c:\SQLLIB\java\db2java.zip file. This filemust be available to Java through the class path.

Department.csv"A00","SPIFFY COMPUTER SERVICE DIV.","000010","A00", "SAN JOSE""B01","PLANNING","000020","A00", "SAN JOSE""C01","INFORMATION CENTER","000030","A00", "SAN JOSE""D01","DEVELOPMENT CENTER",,"A00", "SAN JOSE""D11","MANUFACTURING SYSTEMS","000060","D01", "SAN JOSE""D21","ADMINISTRATION SYSTEMS","000070","D01", "SAN JOSE""E01","SUPPORT SERVICES","000050","A00", "SAN JOSE""E11","OPERATIONS","000090","E01", "SAN JOSE""E21","SOFTWARE SUPPORT","000100","E01", "SAN JOSE"

Employee.csv"000010","CHRISTINE","I","HAAS","A00","3978","1965-01-01","PRES",18,"F","1933-08-24", 0052750.00, 0001000.00, 0004220.00"000020","MICHAEL","L","THOMPSON","B01","3476","1973-10-10","MANAGER",18,"M","1948-02-02", 0041250.00, 0000800.00, 0003300.00"000030","SALLY","A","KWAN","C01","4738","1975-04-05","MANAGER",20,"F","1941-05-11", 0038250.00, 0000800.00, 0003060.00"000050","JOHN","B","GEYER","E01","6789","1949-08-17","MANAGER",16,"M","1925-09-15", 0040175.00, 0000800.00, 0003214.00"000060","IRVING","F","STERN","D11","6423","1973-09-14","MANAGER",16,"M","1945-07-07", 0032250.00, 0000500.00, 0002580.00"000070","EVA","D","PULASKI","D21","7831","1980-09-30","MANAGER",16,"F","1953-05-26", 0036170.00, 0000700.00, 0002893.00"000090","EILEEN","W","HENDERSON","E11","5498","1970-08-15","MANAGER",16,"F","1941-05-15", 0029750.00, 0000600.00, 0002380.00"000100","THEODORE","Q","SPENSER","E21","0972","1980-06-19","MANAGER",14,"M","1956-12-18", 0026150.00, 0000500.00, 0002092.00"000110","VINCENZO","G","LUCCHESSI","A00","3490","1958-05-16","SALESREP",19,"M","1929-11-05", 0046500.00, 0000900.00, 0003720.00"000120","SEAN"," ","O'CONNELL","A00","2167","1963-12-05","CLERK",14,"M","1942-10-18", 0029250.00, 0000600.00, 0002340.00"000130","DOLORES","M","QUINTANA","C01","4578","1971-07-28","ANALYST",16,"F","1925-09-15", 0023800.00, 0000500.00, 0001904.00"000140","HEATHER","A","NICHOLLS","C01","1793","1976-12-15","ANALYST",18,"F","1946-01-19", 0028420.00, 0000600.00, 0002274.00"000150","BRUCE"," ","ADAMSON","D11","4510","1972-02-02","DESIGNER",16,"M", "1947-05-17", 0025280.00, 0000500.00, 0002022.00

26 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 51: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Oracle 8 InstallationWe have installed a standard developer installation of Oracle Version 8.0.4under Windows NT.

Oracle Database SetupWe assume that Oracle is installed. We are now going to create the tables ofthe itsowdb database, and fill the tables with sample data.

User IDBy convention, all tables are created under the ITSO user ID, so the firstthing to do is to create the ITSO user. To do that, open the Oracle 8Navigator. In the tree go all the way down to the User node (Figure 13).

In the General Pane create the user ITSO with password itso; in thePrivileges Pane give the new ITSO user additionally the Resource Role(Figure 14).

In our installation the Oracle installer did not copy the JDBC driver files.Make sure those driver files are installed if you plan to access an Oracledatabase using JDBC. We copied the driver files manually from theinstallation CD from win32/v8/Jdbc to c:\orant\Jdbc, which was the home ofour Oracle8 installation.

Moreover, if you later want to use the OCI Driver (see “Oracle OCI Driver”on page 46) you either have to put c:\orant\Jdbc\lib in the system path orplace the oci804jdbc.dll somewhere in the path, for example,c:\WinNT\system32.

Notice

Chapter 4. Relational Database Installation and Setup 27

Page 52: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 13. Creating a New User for Oracle

Figure 14. Assigning a Role to an Oracle User

28 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 53: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Oracle Table CreationNow that the user is created, the next step is to create the database tables.You will notice that we have not yet created a database ourselves. During theinstallation of Oracle, a database is created that holds all the tables.

Figure 15 lists the SQL statements used to create the ITSOWDB tables.

Figure 15. Oracle Table Creation

CONNECT itso/itso;

DROP TABLE ITSO.EMPLOYEE;DROP TABLE ITSO.DEPARTMENT;

----------------- DDL Statements for table ITSO.DEPARTMENT

CREATE TABLE ITSO.DEPARTMENT ( DEPTNO CHAR(3) NOT NULL , DEPTNAME VARCHAR(29) NOT NULL , MGRNO CHAR(6) , ADMRDEPT CHAR(3) NOT NULL , LOCATION CHAR(16) );

ALTER TABLE ITSO.DEPARTMENT ADD PRIMARY KEY (DEPTNO);

----------------- DDL Statements for table ITSO.EMPLOYEE

CREATE TABLE ITSO.EMPLOYEE ( EMPNO CHAR(6) NOT NULL , FIRSTNME VARCHAR(12) NOT NULL , MIDINIT CHAR(1) NOT NULL , LASTNAME VARCHAR(15) NOT NULL , WORKDEPT CHAR(3) , PHONENO CHAR(4) , HIREDATE DATE , JOB CHAR(8) , EDLEVEL SMALLINT NOT NULL , SEX CHAR(1) , BIRTHDATE DATE , SALARY DECIMAL(9,2) , BONUS DECIMAL(9,2) , COMM DECIMAL(9,2) );

ALTER TABLE ITSO.EMPLOYEE ADD PRIMARY KEY (EMPNO);

----------------- DDL Statement for foreign key relationship

ALTER TABLE EMPLOYEE ADD FOREIGN KEY (WORKDEPT) REFERENCES DEPARTMENT (DEPTNO);

COMMIT;

Chapter 4. Relational Database Installation and Setup 29

Page 54: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

To create the tables, start the SQL Plus 8.0 tool from the Start menu.Connect as user ITSO with password itso. You will use the itsowdb.ddl filefrom the Oracle directory. From the SQL> prompt, issue the command:

start c:\WasDbBk\dbase\Oracle\itsowdb.ddl

Use the correct path for the SQL file for your installation. Figure 16 displaysthe result when you issue the start command to execute the SQL.

Figure 16. Oracle Table Creation Output

Now your tables are set up to import the actual data. To do that, use theOracle8 Navigator again. Expand the tree until you see the new tables in thelocal databases. You should have at least one table named DEPARTMENTand one named EMPLOYEE. Because the default installation of Oracle8installs tables with the same names, make sure you import the data to thecorrect tables. Verify this by inspecting that owner of the tables is ITSO.

30 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 55: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Importing the Table Data into OracleImport the data by selecting Import From File (Figure 17). Then specify thedata file, which is either employee.csv for the employee table ordepartment.csv for the department table. Both files reside in the samedirectory as the itsowdb.ddl file (c:\WasDbBk\dbase\Oracle).

Figure 17. Import Data For The Employee Table

The sample data files are almost identical to the files used for DB2. Anextract of the sample data is shown in Figure 18.

The format of the date columns is different, 01-JAN-1965 instead of 1965-01-01.To distinguish results of queries, we use employee numbers starting with thenumber 1, that is, 100010 instead of 000010.

Chapter 4. Relational Database Installation and Setup 31

Page 56: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 18. Oracle Sample Data Extract

The database is now ready. You may verify this by selecting one of the tables(right click) and open it.

Oracle JDBC DriversThe Oracle JDBC drivers are in the c:\orant\jdbc\lib\classes111.zip file. Thisfile must be available to Java through the class path.

Department.csv"A00","SPIFFY COMPUTER SERVICE DIV.","100010","A00", "SAN JOSE""B01","PLANNING","100020","A00", "SAN JOSE""C01","INFORMATION CENTER","100030","A00", "SAN JOSE""D01","DEVELOPMENT CENTER",,"A00", "SAN JOSE""D11","MANUFACTURING SYSTEMS","100060","D01", "SAN JOSE""D21","ADMINISTRATION SYSTEMS","100070","D01", "SAN JOSE""E01","SUPPORT SERVICES","100050","A00", "SAN JOSE""E11","OPERATIONS","100090","E01", "SAN JOSE""E21","SOFTWARE SUPPORT","100100","E01", "SAN JOSE"

Employee.csv"100010","CHRISTINE","I","HAAS","A00","3978","01-JAN-1965","PRES",18,"F","24-AUG-1933", 0052750.00, 0001000.00, 0004220.00"100020","MICHAEL","L","THOMPSON","B01","3476","10-OCT-1973","MANAGER",18,"M","02-FEB-1948", 0041250.00, 0000800.00, 0003300.00"100030","SALLY","A","KWAN","C01","4738","05-APR-1975","MANAGER",20,"F","11-MAY-1941", 0038250.00, 0000800.00, 0003060.00"100050","JOHN","B","GEYER","E01","6789","17-AUG-1949","MANAGER",16,"M","15-SEP-1925", 0040175.00, 0000800.00, 0003214.00"100060","IRVING","F","STERN","D11","6423","14-SEP-1973","MANAGER",16,"M","07-JUL-1945", 0032250.00, 0000500.00, 0002580.00"100070","EVA","D","PULASKI","D21","7831","30-SEP-1980","MANAGER",16,"F","26-MAY-1953", 0036170.00, 0000700.00, 0002893.00"100090","EILEEN","W","HENDERSON","E11","5498","15-AUG-1970","MANAGER",16,"F","15-MAY-1941", 0029750.00, 0000600.00, 0002380.00"100100","THEODORE","Q","SPENSER","E21","0972","19-JUN-1980","MANAGER",14,"M","18-DEC-1956", 0026150.00, 0000500.00, 0002092.00"100110","VINCENZO","G","LUCCHESSI","A00","3490","16-MAY-1958","SALESREP",19,"M","05-NOV-1929", 0046500.00, 0000900.00, 0003720.00"100120","SEAN"," ","O'CONNELL","A00","2167","05-DEC-1963","CLERK",14,"M", "18-OCT-1942", 0029250.00, 0000600.00, 0002340.00"100130","DOLORES","M","QUINTANA","C01","4578","28-JUL-1971","ANALYST",16,"F","15-SEP-1925", 0023800.00, 0000500.00, 0001904.00"100140","HEATHER","A","NICHOLLS","C01","1793","15-DEC-1976","ANALYST",18,"F","19-JAN-1946", 0028420.00, 0000600.00, 0002274.00"100150","BRUCE"," ","ADAMSON","D11","4510","12-FEB-1972","DESIGNER",16,"M", "17-MAY-1947", 0025280.00, 0000500.00, 0002022.00

32 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 57: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SQL Server InstallationWe installed SQL Server Version 7.0 Desktop. Before you proceed with theinstallation you should go to the Installation Pre-requisite section. Check andmake sure the Internet Explorer version you have is equal or greater than theversion mentioned in the pre-requisite. If you have an older version, proceedwith the prerequisite installation and then go and install the SQL server.

SQL Server Database SetupThere are a few steps you must follow to enable access to SQL Server throughWebSphere. Because SQL Server does not provide a JDBC driver, we use theSun JDBC/ODBC bridge to get a connection to the database.

Create ITSOWDB DatabaseThe first step is to create our database:

❑ Open the SQL Server Enterprise Manager.

❑ Expand ConsoleRoot -> Microsoft SQL Server -> SQL Server Group ->[Computer-Name] -> Databases and select New Database from the contextmenu (Figure 19).

Figure 19. Create a New Database

Chapter 4. Relational Database Installation and Setup 33

Page 58: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Now enter the database name ITSOWDB in the Name: entry field andclick OK.

Setup User ID as OwnerTo create the database tables with the ITSO schema you have to add theITSO user ID into the list of Logins as follows:

❑ From Enterprise Manager expand ConsoleRoot -> Microsoft SQL Server ->SQL Server Group -> [Computer-Name] and open Security.

❑ Right mouse click on Logins and select New Login.

❑ Input ITSO as the Name and select your Domain under Authentication.

❑ Under Defaults for Database select ITSOWDB.

❑ Select Server Roles tab and check System Administrators.

❑ Select Database Access, check ITSOWDB and check public and db_owneras database roles. Now click on the OK button.

SQL Server Table CreationTo create the tables for SQL Server we run the DDL commands in thec:\WasDbBk\dbase\SQLServer\itsowdb.ddl file. To run this file you have to run theQuery Analyzer. This is a separate SQL Server tool found from WindowsStart -> Programs -> SQL Server, or from the SQL Server Enterprise managerselect Tools -> SQL Query Analyzer. Open the file and run it (Figure 20).

Make sure to select the ITSOWDB database from the list of databases on thetop menu bar.

34 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 59: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 20. SQL Server Table Creation

Importing the Table Data into SQL ServerWe now have to fill our tables with content. The easiest way to do this is touse the import/export wizard. From the Microsoft SQL Server 7.0 programgroup start Import and Export Data. Skip the entry panel with theintroduction text and proceed to the second panel.

DROP TABLE ITSO.EMPLOYEE;DROP TABLE ITSO.DEPARTMENT;

----------------- DDL Statements for table ITSO.DEPARTMENT

CREATE TABLE ITSO.DEPARTMENT ( DEPTNO CHAR(3) NOT NULL , DEPTNAME VARCHAR(29) NOT NULL , MGRNO CHAR(6) , ADMRDEPT CHAR(3) NOT NULL , LOCATION CHAR(16) );

ALTER TABLE ITSO.DEPARTMENTADD PRIMARY KEY (DEPTNO);

----------------- DDL Statements for table ITSO.EMPLOYEE

CREATE TABLE ITSOWDB.ITSO.EMPLOYEE ( EMPNO CHAR(6) NOT NULL , FIRSTNME VARCHAR(12) NOT NULL , MIDINIT CHAR(1) NOT NULL , LASTNAME VARCHAR(15) NOT NULL , WORKDEPT CHAR(3) , PHONENO CHAR(4) , HIREDATE DATETIME , JOB CHAR(8) , EDLEVEL SMALLINT NOT NULL , SEX CHAR(1) , BIRTHDATE DATETIME , SALARY DECIMAL(9,2) , BONUS DECIMAL(9,2) , COMM DECIMAL(9,2) );

ALTER TABLE ITSO.EMPLOYEEADD PRIMARY KEY (EMPNO);

----------------- DDL Statement for foreign key relationship

ALTER TABLE ITSO.EMPLOYEE ADD FOREIGN KEY (WORKDEPT) REFERENCES ITSO.DEPARTMENT (DEPTNO);

Chapter 4. Relational Database Installation and Setup 35

Page 60: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Make sure you select Text File as the source. Then specify the path(c:\WasDbBk\dbase\SQLServer) where the csv files are located (Figure 21).

Figure 21. Import Data for Department Table

❑ In the next panel you may specify the file format of the text file that is tobe imported. It should not be necessary to make any changes.

❑ Then you may specify the column separator. Again the default should besufficient.

❑ Figure 22 shows the next step. Be sure to select the correct database asthe import destination.

36 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 61: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 22. Choose a Destination

❑ Now the destination table has to be specified. In this case we import thedepartment data into the department table as destination (Figure 23).

Figure 23. Select the Destination Table

❑ In the next step you may specify additional options, for example, if thisimport process should be stored. We skip this step and click Next.

❑ The wizard shows its last panel, informing us that the import process isnow specified and ready to run. Click Finish. If everything runs fine, SQLServer will inform you with a message box (Figure 24).

Chapter 4. Relational Database Installation and Setup 37

Page 62: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 24. Importing Data Was Successful

The same import has to be performed for the employee table using theemployee.csv file.

The sample data files are identical to the files used for Oracle (Figure 18 onpage 32), with the exception that we used employee numbers starting withthe number 2, that is, 200010 instead of 100010.

SQL Server JDBC DriversSQL Server does not provide JDBC drivers. We use the JDBC/ODBC bridgedrivers provided by Sun in the JDK. To use the bridge we have to set up anODBC data source.

ODBC Data Source Setup for JDBCTo enable the ITSOWDB database for ODBC or for the JDBC/ODBC bridge,you have to set up an ODBC data source:

❑ Go to the Control Panel and open ODBC Data Sources.

❑ In the ODBC Data Source Administrator select the System DSN tab(Figure 25).

38 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 63: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 25. ODBC Data Source Administrator

❑ Select Add to add a new DSN (Figure 26).

Figure 26. Create New Data Source

Chapter 4. Relational Database Installation and Setup 39

Page 64: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Select SQLServer and click on Finish.

❑ Enter the name, description, and server for the Data Source Name, thenclick Next (Figure 27).

Figure 27. Create New Data Source to SQL Server

❑ Now specify what kind of authorization you want the database to use andthen click on Next.

❑ Next you select the ITSOWDB database for the ODBC connection. Clickon Next (Figure 28).

40 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 65: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 28. Create New Data Source to SQL Server (Database Setup)

❑ On the ODBC Microsoft SQL Server Setup Panel click on Test Data Sourceto confirm that your selections were correct and that the connection can beestablished. Then click on Finish.

You must make sure to set up a System DSN and not a User DSN. If youset up a User DSN you will not be able to establish a connection to SQLserver through WebSphere, because it is using a default system ID to gainaccess.

Note

Chapter 4. Relational Database Installation and Setup 41

Page 66: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

42 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 67: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

5 Java DatabaseConnectivitySun developed the Java Database Connectivity (JDBC) data access layer tokeep the Java API for accessing relational databases standard across allvendors. Similar to Microsoft’s ODBC, this layer provides Java programmersa generic way to communicate with relational databases regardless of thedatabase vendor.

Most vendors provide JDBC drivers for their products, which enables you toaccess the vendor’s database using the JDBC API. For more detailedinformation on JDBC drivers and categories of drivers, refer to the IBMredbook Application Development with VisualAge for Java Enterprise,SG24-5081.

© Copyright IBM Corp. 1999 43

Page 68: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2 UDB JDBC DriversIBM provides two JDBC drivers for standard access to DB2. Each wasdeveloped by utilizing previously written software, so each implements theconnection differently. The drivers are shipped with DB2 UDB and arelocated in the file:

c:\SQLLIB\java\db2java.zip

When testing your JDBC applications, this file must be accessible in the Javaclass path, or your application will not be able to find the JDBC drivers.

DB2 Application DriverThe DB2 application driver is in the COM.ibm.db2.jdbc.app.DB2Driverclass, located in the db2java.zip class collection file. This driver usesthe URL format of

jdbc:db2:<database name> (jdbc:db2:itsowdb)

Known as a category (or type) 2 JDBC driver, this driver takes advantage of apreviously written database client software. It contains a JDBC bridge thatcloses the gap between the new Java coded driver and the legacy client accesssoftware. The bridge takes JDBC commands and translates them into thetraditional commands used in the client software. In DB2’s case, the DB2Client Application Enabler (CAE) is used (Figure 29). The JDBC driversmust have CAE code libraries available to access the server.

Figure 29. Category 2 JDBC Driver, Vendor Specific Bridge

When the JDBC bridge accesses CAE code, the client is accessing non-Javacode libraries. This driver is not used for communication between client and

CLIENT SERVER

Application

JDBC Driver Manager

JDBC Vendor SpecificData Access Bridge

Client ApplicationEnabler (CAE)

DBMS Server

44 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 69: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

server across a network because of its use of platform dependent code. This isbecause you cannot package the non-Java, platform specific code, into a JARfile to send to a client when the client requests direct access to anindependent database server.

DB2 Network DriverThe network driver is in the COM.ibm.db2.jdbc.net.DB2Driver class, alsolocated in the db2java.zip class collection. It has a URL of the format:

jdbc:db2://<hostname>:<port>/<database> (jdbc:db2://sonoma:6789/itsowdb)

This driver is known as a category 3 JDBC driver, which splits the drivercode between the client and the server. The client contains the pure Javacode and the server contains the platform specific code. When a database callis issued, the client translates the call into a generic network protocol. Theserver then translates the call back into a JDBC call and processes the call onthe server. Because the client is pure Java, this is a good implementation fornetwork use (Figure 30).

Figure 30. Category 3 JDBC Driver, Generic Network Protocol

These drivers require software on the server, also known as middleware, tofulfill the database request and return the result to the client; for DB2 this isthe DB2 JDBC applet server. You must start this service on the server fromthe Services menu in the Control Panel, it uses the default port number of6789. You can also start it from a DOS command prompt by issuing thecommand:

db2jstrt <port number> (db2jstrt 6789)

JDBC Driver Manager

JDBC Generic Network Protocol Driver

Middleware Middleware

DBMS (DB2) DBMS (other)

Application

Chapter 5. Java Database Connectivity 45

Page 70: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Oracle JDBC DriversOracle provides two categories of JDBC, a thin client driver which is pureJava and a second driver known as the Oracle Call Interface (OCI) driver.The OCI driver is not pure Java and uses platform-specific native methods toaccess the database.

Both drivers are implemented in the oracle.jdbc.driver.OracleDriver class.

Oracle Thin Client DriverThe thin client driver is a type 4 client driver which requires only sockets toconnect to an Oracle database. The driver is completely implemented in Java,so it is platform neutral and does not require any Oracle software to beinstalled on the client.

A type 4, according to the definition of JavaSoft, is a native-protocol fullyJava technology-enabled driver.

The URL to access a database through the thin client is:

jdbc:oracle:thin:@<servername>:<portnumber>:<databasename>

In our examples we use the default database instance orcl and the defaultport number 1521, therefore the resulting URL is:

jdbc:oracle:thin:@localhost:1521:orcl

Oracle OCI DriverThe OCI driver is a type 2 driver. By definition a category 2, or type 2, driveris a native-API partly Java technology-enabled driver (as shown in Figure 29on page 44). It provides an implementation of the JDBC based on the nativeOCI to access the database.

Since native methods are used to interact with the database, the OCI driveris platform specific. Although this driver is not suitable for applets, the OCIdriver has the advantage of better performance. This makes it ideal for beingused by servlets on the server. As we tested, both drivers work withWebSphere, provided that the Application Server class path includes theOracle drivers, and that for the OCI driver the oci804jdbc.dll file is in thesystem path (see “Oracle 8 Installation” on page 27).

46 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 71: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The URL to access a database using the OCI driver is somewhat longer:

jdbc:oracle:oci8:@(description=(address=(host=<servername>)(protocol=tcp)(port=<portnumber>))(connect_data= (sid=<databasename>)))

In our examples we use the default database instance orcl and the defaultport number 1521, therefore the resulting URL is:

jdbc:oracle:oci8:@(description=(address=(host=localhost)(protocol=tcp)(port=1521))(connect_data=(sid=orcl)))

SQL Server JDBC DriversMicrosoft does not provide a JDBC driver for SQL Server. JavaSoft doespackage a JDBC/ODBC bridge in the sun.jdbc.odbc.JdbcOdbcDriver class. Ituses a URL format of jdbc:odbc:<ODBC Data Source Name>. Sun’s driver does havea few shortcomings; it is a type 2 driver, which means it cannot be used inapplets. Also it can only connect to local ODBC Data Source Names.

An ODBC Data Source is a system defined way for a driver to connect to anODBC compliant data provider. To use ODBC drivers (or a JDBC/ODBCbridge), you must define an ODBC Data Source Name (DSN) for the dataprovider (for example, SQL Server) so that your driver knows how to retrieveinformation from the data provider. In Windows, you can define an ODBCData Source Name (DSN) by using the ODBC Data Source Administrator,located in the Windows Control Panel. It is possible to define a DSN on yourmachine for a remote server, but access must be granted on the server foryour specific machine name.

Many vendors offer drivers which can connect directly to remote servers, butmost require some middleware to translate the calls from JDBC to ODBC. Acompany named i-net software (www.inetsoftware.de) does offers a category 4driver for SQL Server. This driver has made a positive impression on theJava community, but we have neither tested nor implemented this product. Acategory 4 driver is a pure Java driver that connects directly to the serverand does not require any ODBC setup or use. Category 4 drivers are the mostpreferred drivers.

Chapter 5. Java Database Connectivity 47

Page 72: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Configuring VisualAge for Java for JDBCTo use the databases from within the development environment of VisualAgefor Java, the drivers have to be made visible in VisualAge for Java. There aretwo ways to achieve this.

The first possibility is to include the zip files containing the JDBC drivers inthe class path of VisualAge for Java:

❑ The DB2 zip file is c:\sqllib\java\db2java.zip

❑ The Oracle zip file is c:\orant\Jdbc\lib\classes111.zip

❑ The JDBC/ODBC bridge for SQL Server is part of the standard Sun Javaclasses.

To add the zip files to the class path, open the Options dialog from theWindow menu in VisualAge for Java. Click on Resources on the left side andedit the Workspace class path on the right side, as in Figure 31.

Figure 31. Editing VisualAge for Java’s Class Path

C:\sqllib\db2java.zip;c:\orant\Jdbc\lib\classes111.zip;

48 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 73: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The second possibility is to import the zip files into the repository andWorkbench of VisualAge for Java. This has the advantage that, if later on anapplication or an applet is packed together with the required JDBC drivers,VisualAge for Java will be able to include the drivers in the resulting JARfiles.

To import the zip file use the import feature. Select File -> Import and selectJar-file as input source, browse for the jar file (either db2java.zip orclasses111.zip) and import it, for example under the new project DatabaseJDBC Drivers.

Configuring WebSphere for JDBCTo use the DB2 and Oracle JDBC drivers for servlets within WebSphere it isnecessary to include the driver classes in the WebSphere class path. Open aWeb browser with the WebSphere administration page (http://<server-name or ip-address>:9527), go to Setup -> Java Engine, and add

c:\sqllib\java\db2java.zip (DB2)c:\orant\Jdbc\lib\classes111.zip (Oracle)

to the Application Server Classpath Entry (Figure 32).

Figure 32. JDBC Drivers in WebSphere Class Path

Chapter 5. Java Database Connectivity 49

Page 74: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

50 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 75: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Part 3 DatabaseProgrammingExamples

This part describes all of the code implementations of integrating Websphere,VisualAge for Java, and database managers. These examples are simplifiedto facilitate your understanding of the concepts. After reviewing theseexamples you should have developed the basic knowledge necessary tointegrate Websphere Java servlets and database management systems inmore complex environments.

For all of the development and tests that are not automated by WebSphereStudio, we used IBM’s VisualAge for Java. We recommend the use of thisdevelopment suite for its power, ease of use, and its tight integration withWebSphere. This tight integration provides seamless portability of your codebetween the two products.

© Copyright IBM Corp. 1999 51

Page 76: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

52 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 77: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

6 JDBC ProgrammingExamplesThis chapter briefly describes, through examples, the basics of connectingJava applications and servlets to databases using JDBC. These examplesshould merely be used as building blocks and to understand the concepts.

Simple JDBC ApplicationWe implemented a simple class to handle the common interaction with eachvendor’s databases. This class, shown in Figure 33, was implemented usingVisualAge for Java and created under the itso.wasdb.jdbc package.

The program logic uses the following methods:

❑ makeConnection: creates a connection to the database, prints a messageto the console saying the connection was successful, and then returns theconnection to the caller.

© Copyright IBM Corp. 1999 53

Page 78: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 33. Simple Class for JDBC Access

package itso.wasdb.jdbc;

import java.sql.*;

public class SimpleSQL {

// Instance variable for the URL propertyprivate String url = null;// Instance variable for the userID propertyprivate String userID = null;// Instance variable for the password propertyprivate String password = null;// Instance variable for Connectionprivate Connection con = null;

public void makeConnection() {try {

con = DriverManager.getConnection(url, userID, password);System.out.println("Connected to Database: " + url+"\n");

} catch (SQLException se) {System.out.print(se);

} catch (Exception e) {System.out.println(e);

}return;

}

public void setPassword(String aPassword) {password = aPassword;

}public void setURL(String aUrl) {

url = aUrl;}public void setUserID(String aUserID) {

userID = aUserID;}

public void executeSQL() throws SQLException {Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("Select empno, lastname, deptname, mgrno from itso.employee A, itso.department B where A.workdept = B.deptno");

System.out.println("EMPNO LASTNAME DEPT MGRNO\n");

while (rs.next()) {String s1 = rs.getString("EMPNO");String s2 = rs.getString("LASTNAME").concat(" ").substring(0,14);String s3 = rs.getString("DEPTNAME").concat(" ").substring(0,29);String s4 = rs.getString("MGRNO");System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);}

}

}

54 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 79: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ setXXX: methods to set the database connection parameters.

❑ executeSQL: executes an SQL statement and displays the result set to theconsole. This SQL statement performs an inner join of the two tablesbased on the employee’s department. It displays the employee number,last name, work department, and the department manager’s employeenumber, as shown in the output (Figure 34).

Note that for this simplified example, we are not catching all possibleexceptions.

Figure 34. JDBC Example Output

Connected to Database: jdbc:db2:itsowdb

EMPNO LASTNAME DEPT MGRNO

000010 HAAS SPIFFY COMPUTER SERVICE DIV. 000010000120 O'CONNELL SPIFFY COMPUTER SERVICE DIV. 000010000110 LUCCHESSI SPIFFY COMPUTER SERVICE DIV. 000010000020 THOMPSON PLANNING 000020000030 KWAN INFORMATION CENTER 000030000140 NICHOLLS INFORMATION CENTER 000030000130 QUINTANA INFORMATION CENTER 000030000060 STERN MANUFACTURING SYSTEMS 000060000220 LUTZ MANUFACTURING SYSTEMS 000060000210 JONES MANUFACTURING SYSTEMS 000060000200 BROWN MANUFACTURING SYSTEMS 000060000190 WALKER MANUFACTURING SYSTEMS 000060000180 SCOUTTEN MANUFACTURING SYSTEMS 000060000170 YOSHIMURA MANUFACTURING SYSTEMS 000060000160 PIANKA MANUFACTURING SYSTEMS 000060000150 ADAMSON MANUFACTURING SYSTEMS 000060000070 PULASKI ADMINISTRATION SYSTEMS 000070000270 PEREZ ADMINISTRATION SYSTEMS 000070000260 JOHNSON ADMINISTRATION SYSTEMS 000070000250 SMITH ADMINISTRATION SYSTEMS 000070000240 MARINO ADMINISTRATION SYSTEMS 000070000230 JEFFERSON ADMINISTRATION SYSTEMS 000070000050 GEYER SUPPORT SERVICES 000050000090 HENDERSON OPERATIONS 000090000310 SETRIGHT OPERATIONS 000090000300 SMITH OPERATIONS 000090000290 PARKER OPERATIONS 000090000280 SCHNEIDER OPERATIONS 000090000100 SPENSER SOFTWARE SUPPORT 000100000340 GOUNOT SOFTWARE SUPPORT 000100000330 LEE SOFTWARE SUPPORT 000100000320 MEHTA SOFTWARE SUPPORT 000100

Chapter 6. JDBC Programming Examples 55

Page 80: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2 Universal Database JDBC Code ExampleWe use both the application driver (com.ibm.db2.jdbc.app.DB2Driver) andthe network driver (com.ibm.db2.jdbc.net.DB2Driver) in Figure 35 toillustrate the coding of each driver.

For the network driver, you must remember to start the JDBC applet serveron the server machine. This network driver uses a generic network protocolto send its request to the server, then platform specific code on the servertranslates the call to the database manager. See “DB2 Network Driver” onpage 45 for further details.

The port specified in the network driver’s URL must correspond to the portdefined when the middleware on the server (DB2 JDBC applet server) isstarted.

Figure 35. DB2 UDB JDBC Code Example

package itso.wasdb.jdbc;

public class Db2SQL {

public static void main(java.lang.String[] args) {SimpleSQL udbSQL = new SimpleSQL();SimpleSQL udbSQLnet = new SimpleSQL();String drv = "COM.ibm.db2.jdbc.app.DB2Driver";String drvnet = "COM.ibm.db2.jdbc.net.DB2Driver";

try {Class.forName(drv).newInstance();udbSQL.setUserID("itso");udbSQL.setPassword("itso");udbSQL.setURL("jdbc:db2:itsowdb");udbSQL.makeConnection();udbSQL.executeSQL();

// You must start the JDBC Applet Server on the server machine with port 2222. // Issue db2jstrt 2222 from command prompt

Class.forName(drvnet).newInstance();udbSQLnet.setUserID("itso");udbSQLnet.setPassword("itso");udbSQLnet.setURL("jdbc:db2://SONOMA:2222/itsowdb");udbSQLnet.makeConnection();udbSQLnet.executeSQL();

} catch (Exception e) {System.out.println(e);

}}

56 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 81: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Oracle JDBC Code ExampleThe Oracle example is straightforward and differs only in the usage of thedrivers. We used both Oracle JDBC drivers (Figure 36).

We assume a standard installation of Oracle with the default settings:

❑ The Oracle server is located on the same machine where the example isrunning. If Oracle is running on another machine, localhost must bereplaced by the name of the appropriate machine.

❑ The database instance is the default instance which is created duringinstallation of Oracle, namely orcl. If other database instances are used,this is to be replaced by the appropriate names.

❑ The default port number 1521 is used for the Oracle server listener. Thiscan be changed in the Oracle Net8 Assistant tool.

Figure 36. Oracle JDBC Code Example

package itso.wasdb.jdbc;

public class OracleSQL {

public static void main(String args[]) {SimpleSQL orclThinSql = new SimpleSQL();SimpleSQL orclOciSql = new SimpleSQL();

String drv = "oracle.jdbc.driver.OracleDriver";String urlThin = "jdbc:oracle:thin:@localhost:1521:orcl";String urlOci = "jdbc:oracle:oci8:@(description=(address=(host=localhost)

(protocol=tcp)(port=1521))(connect_data=(sid=orcl)))";

try {Class.forName(drv).newInstance();

// First try the thin driver orclThinSql.setUserID("itso");

orclThinSql.setPassword("itso");orclThinSql.setURL(urlThin);orclThinSql.makeConnection();orclThinSql.executeSQL();

// Now try the OCI driver orclOciSql.setUserID("itso");

orclOciSql.setPassword("itso");orclOciSql.setURL(urlOci);orclOciSql.makeConnection();orclOciSql.executeSQL();

} catch (Exception e) { System.out.println(e); }}}

Chapter 6. JDBC Programming Examples 57

Page 82: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SQL Server JDBC Code ExampleWe decided to use Sun’s JDBC/ODBC bridge driver for our example. Itprovides limited functionality but is sufficient for our testing. When using aJDBC/ODBC Bridge, it is important to create an ODBC Data Source Name(DSN) for your data server. In Windows NT, go to the Control Panel andselect ODBC Data Sources.

Because we are using Sun’s driver, we must use a user DSN to access ourdatabase. In the Data Sources panel, select the Add button to add a DSN forSQL Server. A prompt for the data source will appear, and if SQL Server isinstalled, it will be listed as a possible source. You must specify a name,description, and a server. You can enter a remote server by entering theremote server computer name. This is the only way to connect to a remoteserver if you are using Sun’s driver. The next screen will prompt you on howto check the authority of a login ID. For remote server authentication youshould select SQL Server for authorization as in Figure 37. You should alsoadd this ID to the SQL Server running on the remote computer.

Figure 37. ODBC DSN Authorization

The rest of the setup is self-explanatory; we chose the default settings for allother panels. When you are done, you should have a new Data Source Name.In Figure 38 we have already added a local and remote SQL Server.

58 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 83: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 38. ODBC Data Source Administrator

Figure 39 contains the class we used to connect to SQL Server. We instantiatethe driver and then set our parameters. Notice that our URL uses theJDBC/ODBC bridge standard naming convention:

jdbc:odbc:<server name>:<Data Source Name>

Figure 39. SQL Server JDBC Example Code

package itso.wasdb.jdbc;

public class SqlSrvSQL {

public static void main(java.lang.String[] args) {SimpleSQL sqlsrvsql = new SimpleSQL();String drv = "sun.jdbc.odbc.JdbcOdbcDriver";try {

Class.forName(drv).newInstance();sqlsrvsql.setUserID("itso");sqlsrvsql.setPassword("itso");sqlsrvsql.setURL("jdbc:odbc:SQLSERVER");sqlsrvsql.makeConnection();sqlsrvsql.executeSQL();

} catch (Exception e) { System.out.println(e); }}}

Chapter 6. JDBC Programming Examples 59

Page 84: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Running Applications with JDBCThe sample JDBC applications can be tested in VisualAge for Java, and theycan be run outside of VisualAge for Java in the operating system.

Testing the JDBC Applications in VisualAge for JavaTo execute the sample applications in VisualAge for Java, make sure that theJDBC drivers are in the class path. See “Configuring VisualAge for Java forJDBC” on page 48 for detailed instructions.

Select the Java class of the application and click on the Run icon in the toolbar. You can also select Run -> Run main from the context menu. The outputof the application is displayed in the VisualAge for Java Console window.

Note: The Oracle OCI driver does not work in VisualAge for Java. It seemsthat the required DLL cannot be loaded.

Running the JDBC Applications in the Operating SystemA Java JDK must be installed in the operating system. To run the sampleapplications, export the classes from VisualAge for Java into a directory thatis in the Java class path of the operating system.

We exported the classes into the c:\WasDbBk\code directory. This operationcreates subdirectories matching the package name of the classes, that is,c:\WasDbBk\code\itso\wasdb\jdbc.

Class Path for Java ApplicationsThe class path must include the JDBC drivers and the exported code. Wechanged the operating system CLASSPATH environment variable from theControl Panel -> System icon to include:

c:\sqllib\java\db2java.zipc:\orant\jdbc\lib\classes111.zipc:\WasDbBk\code

Run the JDBC ApplicationTo execute the JDBC applications, open a command window and enter:

java itso.wasdb.jdbc.Db2SQLjava itso.wasdb.jdbc.OracleSQLjava itso.wasdb.jdbc.SqlSrvSQL

60 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 85: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Simple JDBC ServletWe implemented a simple JDBC servlet to gain experience with theWebSphere Test Environment of VisualAge for Java and with deployment ofthe code to the WebSphere Application Server.

Our servlet consists of two classes:

❑ DbServletBean: a bean that contains all the JDBC code to list theemployees of the employee table.

❑ DbServlet: a servlet that accepts a parameter to select the databasemanagement system and then calls the bean to execute the JDBC code.

The servlet (DbServlet) contains a doGet method that is called from the Webserver’s servlet engine (Figure 40).

The servlet sets up the bean with the JDBC driver, URL, user ID, andpassword, before calling the execute method to run the JDBC code. Aparameter named database is passed to the servlet to select the databasemanagement system (DB2, Oracle, or SQLServer).

The JDBC bean (DbServletBean) contains the following methods:

❑ setURL: to set the value of the database URL

❑ setUserID: to set the user ID for the connection

❑ setPassword: to set the password for the connection

❑ makeConnection: to connect to the database using the URL, user ID, andpassword

❑ executeSQL: to execute the select statement:

select empno, lastname, deptname, mgrno from itso.employee A, itso.department Bwhere A.workdept = B.deptno

❑ outputInfo: to create the HTML table with the result of the select

We do not show the code of the JDBC bean here because it is very similar tothe simple JDBC application. The only difference is that the output is routedback to the Web server instead of being written to the console.

Chapter 6. JDBC Programming Examples 61

Page 86: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 40. Simple Servlet doGet Method

public class DbServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res){String drv = " ", url = " ";String database = req.getParameterValues("database")[0];if (database.equals("DB2")) {

drv = "COM.ibm.db2.jdbc.app.DB2Driver";url = "jdbc:db2:itsowdb";

}else if (database.equals("Oracle")) {

drv = "oracle.jdbc.driver.OracleDriver";url = "jdbc:oracle:thin:@localhost:1521:orcl";

}else if (database.equals("SQLServer")) {

drv = "sun.jdbc.odbc.JdbcOdbcDriver";url = "jdbc:odbc:SQLSERVER";

}PrintWriter out = null;DbServletBean dbBean = new DbServletBean();try {

out = res.getWriter();out.println("<HTML><BODY>");Class.forName(drv).newInstance();

dbBean.setUserID("itso");dbBean.setPassword("itso");dbBean.setURL(url);out.println("<h1>--------- Attempting to Connect -------</h1><p>");out.println("URL: "+ url + "<br>Driver: "+drv);dbBean.makeConnection();out.println("<h1>--------- Connection was successful -------</h1><p>");dbBean.executeSQL(out);

}catch(SQLException sqlExcept) {

out.println("<h1>------ EXCEPTION IN SAMPLE CODE ------</h1><p>");out.println("Error:" + sqlExcept.getErrorCode());out.println("State:" + sqlExcept.getSQLState());sqlExcept.printStackTrace(out);

}catch (Exception except) {

out.println("<h1>------ EXCEPTION IN SAMPLE CODE ------</h1><p>");out.println(except);except.printStackTrace(out);

}out.println("<HTML><BODY>");

}

}

62 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 87: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Testing the Servlet in VisualAge for JavaStart the WebSphere Test Environment (review “Running Servlets inVisualAge for Java” on page 12).

To run the servlet you open a Netscape browser and enter the URL:

http://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=DB2http://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=Oraclehttp://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=SQLServer

Alternatively you can set up the servlet database parameter through theservlet launcher properties dialog in VisualAge for Java (select the servletclass and Tools -> Servlet Launcher -> Properties). Enter the parameter name(database) and the value (DB2, Oracle, or SQLServer). Then launch theservlet by selecting Tools -> Servlet Launcher -> Launch. This starts a Webbrowser with the correct URL.

The output of the servlet is shown in Figure 41.

Running the Servlet in WebSphereTo deploy the servlet to WebSphere export the classes to the WebSphereservlets directory (c:\WebSphere\AppServer\servlets).

Make sure that the JDBC drivers are in the WebSphere class path (review“WebSphere Configuration for JDBC” on page 7).

Open a Web browser and enter the URL:

http://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=DB2http://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=Oraclehttp://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=SQLServer

The output of the servlet is shown in Figure 41.

Chapter 6. JDBC Programming Examples 63

Page 88: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 41. Simple Servlet Output in a Web Browser

64 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 89: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

7 IBM ConnectionManagerThe introductory text in this chapter is reprinted from the December 1998issue of the IBM Developer Connection Technical Magazine.

The connection manager provides the means to manage pool(s) of connectionsto one or more database(s). It classes are made of wrapper classes around theclasses over java.sql classes. Having these wrapper classes, JDBCconnections are passed to applications requesting connection.

The goal of the connection manager is to reduce the percentage of resourcesused by the nonproductive connect/disconnect overhead, so that theseresources are available to handle more traffic. The connection manager alsoprovides a way to allocate relational database resources so that during peakrequest volumes the more critical servlets have greater access to thedatabase resources than less critical servlets.

Performance and scalability are two of the most advantages of the connectionmanager. A servlet needing a connection to a relational database will get anexisting connection from the pool, through the connection manager, ratherthan having to create a new connection on its own. This is the key to theconnection manager's role: connections are kept open and are reused, so the

© Copyright IBM Corp. 1999 65

Page 90: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

connect/disconnect overhead is spread over many, entirely separate userrequests coming in over the Internet. WebSphere makes the connection poolmanagement scalable by allowing the connection pool parameters to bemodified dynamically. Figure 42 shows the interaction between theconnection manager and a servlet.

Figure 42. Interaction Flow Between the Connection Manager and a Servlet

Servlets which are using the connection manager can run inside VisualAgefor Java using the WebSphere Test Environment or outside using WebSphereitself.

66 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 91: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

ConfigurationThe connection pools are configurable through the WebSphere ApplicationServer Administrator panel (Figure 43). For information on how to get to theAdministrator panel please refer to “WebSphere Configuration” on page 6.

Figure 43. Connection Management on WebSphere

Connection PoolThere is a set of pre-defined connection pools provided as default for databaseservers such as:

❑ IBM DB2 ❑ Oracle ❑ Informix ❑ Microsoft SQL Server ❑ Sybase

You can customize your pool by adding a new one to the list or edit anexisting one (Figure 44).

It is also possible to add multiple entries differing in the pool name fordifferent databases of the same vendor. This is even more likely. For example,one could add a pool entry specifying that the database(s) addressed by this

Chapter 7. IBM Connection Manager 67

Page 92: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

pool have longer lasting time out than other databases, addressed by otherpool entries, because the user interaction in a transaction is longer.

Figure 44. Connection Pool Configuration

These are the parameters that can be set for the connection pool:

Pool Type: The type of data server used by this pool of connections. JDBCindicates a JDBC-compliant database. A data server is a product that helpsyou manage and access data. Usually, it is a relational DBMS such as DB2,Oracle, Informix, or Sybase.

Pool Name: The unique name for this pool of connections. Servletprogrammers need to know this name for their servlets to use this connectionpool.

Maximum Connections: Maximum number of connections that can be inthe pool. Consider setting it to the maximum number of users permitted byyour DBMS product license agreement.

Minimum Connections: The minimum number of connections that canremain in the pool as a result of the reap process. The connection managerperiodically removes connections that become idle or orphaned. Use thissetting to keep from removing too many connections, erasing resource usageperformance gains.

Connection Time Out: The length of time (in milliseconds) the connectionmanager will wait for a connection to become free when all connections in thepool are currently in use and the number of connections has reached themaximum (meaning no new connections can be created to fulfill the need).

68 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 93: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ A value of 0 allows the connection manager to wait forever. ❑ A value of -1 disables the wait (an exception is immediately thrown if a

connection is not available). ❑ A value of 1000 to 2000 (1 to 2 seconds) is suggested. ❑ Servlet programmers must know the value of the connection time out to

effectively set the waitRetry parameter in their servlets.

Maximum Age: The maximum number of seconds a connection can be idlebefore the reap process releases the connection from the servlet that owns it.

❑ A value of -1 disables this function; the reap process will not release anyconnections from idle servlets.

❑ A value of 900 to 1800 (15 to 30 minutes) is suggested.

Maximum Idle Time: The maximum number of seconds an unassignedconnection can remain in the pool.

❑ A value of -1 disables this function; the reap process will not remove anyconnection from the pool and disconnect it from the data server.

❑ A value of 900 to 1800 (15 to 30 minutes) is suggested.

Reap Time: The interval (in seconds) at which the connection managerperforms the reap process.

❑ A value of -1 disables this function; the reap will not be performed,regardless of the values specified in Maximum Age or Maximum Idle Timeparameters.

❑ A value of 1800 to 3600 (30 to 60 minutes) is suggested.

IBM Connection Manager and Pure JDBCWhen using standard JDBC for database connection, you are responsible forcreating a new connecting to the database and then closing it. Once theconnection is closed, the next transaction will have to create a newconnection to access the database.

When using the IBM connection manager you get a connection from aconnection pool. If a connection is available the connection manager willreturn a IBMJdbcConnection from which you can obtain its underlyingJDBC connection. When you are done using the connection, you do not closethe connection; you merely release it. This way it can be used by the nextparty requesting a connection to a database. The connection obtainedthrough connection manager should not be closed, that is, do not callConnection.close.

Chapter 7. IBM Connection Manager 69

Page 94: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM Connection Manager ExamplesIn our programming examples we have made connections through theconnection manager using servlets. A select query is run against theemployee table and the result is displayed on a page using HTML. Theconnections have been made to three different databases:

❑ IBM DB2

❑ Oracle

❑ SQL Server

Every database example has its own class. All of the classes related to theconnection manager example are part of the itso.wasdb.connmgr package.The example for all three databases performs the same task. As a result, allthree classes do inherit their common function from a super class. The superclass name is DbaseConnMgr.

When describing the code, only the segments that are relevant to theconnection manager usage are described. The rest is left to the reader’sability to read the code and understand its purpose.

Using the IBM Connection ManagerThe package in which the connection manager classes reside isibm.servlet.connmgr.

There are several steps you must follow to use the connection manager.

❑ Create a connection specification using IBMJdbcConnSpec.

❑ Get a reference to the connection manager object using the static methodIBMConnMgrUtil.getIBMConnMgr.

❑ Get an IBMJdbcConn object, that is, a wrapper around a JDBCconnection, using the connection manager’s getIBMConnection method.

❑ Get a java.sql.Connection Object using getJdbcConnection of the classIBMJdbcConn.

Now you have a connection to the database for your transactions.

Once you are done with the transaction, you have to release the connection tobe returned into the pool. You do this by calling the releaseIBMConnectionmethod of the IBMJdbcConnection class.

70 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 95: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

HTML File for Accessing the ServletsA simple HTML file is used to provide access to launch the servlets throughWebSphere (Figure 45). You have to use this file only when you are trying tolaunch the servlets outside of VisualAge for Java.

Figure 45. HTML for the Connection Manager Servlet Examples

<!DOCTYPE HTML PUBLIC "-//SQ//DTD HTML 2.0 + all extensions//EN" "hmpro3.dtd"><HTML><HEAD> <TITLE> JDBCServlet </TITLE> </HEAD><BODY BGCOLOR="#FFFFFF"><p><table width=580 border=0 cellpadding=20><tr><td valign=top> <H2><center>IBM Connection Manager</center></H2> <P>The following provides an access to three different databases using IBM Connection Manager . </td></tr><tr><td valign=bottom>What would you like to do?<br><br>&nbsp;&nbsp;<A HREF="/servlet/itso.wasdb.connmgr.UdbConnMgr" TARGET="_blank">Run IBM DB2 UDB Sample</A><br>&nbsp;&nbsp;<A HREF="/servlet/itso.wasdb.connmgr.SqlSrvConnMgr" TARGET="_blank">Run MS SqlServer Sample</A><br>&nbsp;&nbsp;<A HREF="/servlet/itso.wasdb.connmgr.OrclConnMgr" TARGET="_blank">Run Oracle Sample</A><br>&nbsp;&nbsp;</td></tr></table></BODY></HTML>

Keep in mind that the connections provided through the connectionmanager are subject to time-outs, depending on the maximum ageparameter. If the difference in the time when you have obtained theconnection and the time when you are going to use it is rather long,compare it to maximum age. It is recommended to useverifyIBMConnection prior to using the connection. If the servlet still ownsthe connection, the method returns true. Otherwise false will be returnedand you have to obtain a new connection object.

Notice

Chapter 7. IBM Connection Manager 71

Page 96: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Running the ExampleThere are two ways in which you can run this sample:

1. Using the WebSphere Test Environment in VisualAge for Java

Select the servlet class, for example itso.wasdb.connmgr.UdbConnMgr,and launch it from the context menu using Tools -> Servlet Launcher ->Launch (Figure 46).

Figure 46. Launching a Servlet

2. Using WebSphere and the HTTP Server

Place the ConnMgrTest.html and the UdbConnMgr.class file under theproper directories. The HTML file has to be placed in the path where theWeb server can find it. Using the default installation the HTML fileshould be placed under c:\Program Files\IBM HTTP Server\htdocs.

The class file can easily exported with VisualAge for Java. From thecontext menu of the servlet class select Export.... In the following dialogselect Directory for the export destination, click Next and specify theexport path. If you use the default installation of WebSphere this isc:\WebSphere\AppServer\servlets. Make sure you select at least the class fileto be exported (Figure 47).

72 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 97: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

For more information about the proper directory location refer to“Configuration” on page 4 and “WebSphere Configuration” on page 6.

Figure 47. Exporting a Servlet

Next go to http://<server-name>/ConnMgrTest.html from the HTML page andselect the database sample you wish to run (you have to export all servletexamples first).

DbaseConnMgr ClassThis class takes care of all function directly involved with the connectionmanager. The following is the class declaration for the DbaseConnMgr class(Figure 48). We then used subclasses for the three different DBMSs.

Figure 48. DbaseConnMgr Class Declaration

The init method initializez the servlet when it is first loaded (Figure 49).

package itso.wasdb.connmgr

import java.sql.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import com.ibm.servlet.connmgr.*;

public abstract class DbaseConnMgr extends HttpServlet {

private static final String SELECT = "Select empno, lastname, deptname, mgrno from itso.employee A,itso.department B where A.workdept = B.deptno ORDER BY A.EMPNO ,B.DEPTNO";

protected IBMJdbcConnSpec connSpec = null;protected IBMConnMgr connMgr = null;

private IBMJdbcConn ibmConn = null; //Connection used for Select statement

private static final String USER = "itso";private static final String PASSWORD = "itso";

}

Chapter 7. IBM Connection Manager 73

Page 98: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 49. DbaseConnMgr init Method

The initConnection method creates a connection manager specification andobtains a static reference to the connection manager object (Figure 50).

Figure 50. DbaseConnMgr initConnection Method

The getConnection method gets an IBMJdbcConnection object from theconnection pool and returns a java.sql.Connection. This connection is used forthe actual SQL statement (Figure 51).

Figure 51. DbaseConnMgr getConnection Method

The releaseConnection method releases the IBMJdbcConnection object intothe connection pool (Figure 52).

public void init(ServletConfig config) throws ServletException {super.init(config);initConnection(getPoolName(), getDriver(), getUrl());

}

private void initConnection(String poolName, String driverName, String url ){

connSpec = new IBMJdbcConnSpec(poolName , true , driverName, url , USER , PASSWORD );

connMgr = IBMConnMgrUtil.getIBMConnMgr();

}

public Connection getConnection() throws SQLException, IBMConnMgrException {Connection conn = null;

ibmConn = (IBMJdbcConn)connMgr.getIBMConnection(connSpec);conn = ibmConn.getJdbcConnection();

return conn;}

74 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 99: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 52. DbaseConnMgr releaseConnection Method

The executeSelect method creates an SQL statement using the connectionobtained from the connection manager and executes it. The result of theexecution is passed on to an output formatting routine (Figure 53).

Figure 53. DBaseConnMgr executeSelect Method

The outputInfo method reads the ResultSet produced by the executeSelectmethod and places it inside a table on the HTML page (Figure 54).

Figure 54. DBaseConnMgr outputInfo Method

The doGet method is called from the Web server when the servlet is startedfrom the HTML page (Figure 55).

public void releaseSelectConnection() throws IBMConnMgrException{ibmConn.releaseIBMConnection();

}

public void executeSelect(PrintWriter out) throws SQLException {

Statement stmt= selConn.createStatement();ResultSet rs = stmt.executeQuery(DB2_SELECT);

outputInfo(rs , out);

}

public void outputInfo(ResultSet rs , PrintWriter out) throws SQLException{

out.println("<TABLE BORDER=3 FRAME=ALL CELLPADDING=1 CELLSPACING=1 COLS=4>");out.println("<CAPTION ALIGN=TOP><b>UDB - Employee Info</b></CAPTION>");

out.println("<TR>");out.println("<TH ALIGN=CENTER WIDTH=20%>Emp Number ");out.println("<TH ALIGN=CENTER WIDTH=20%>Last Name ");out.println("<TH ALIGN=CENTER WIDTH=20%>Dept Name ");out.println("<TH ALIGN=CENTER WIDTH=20%>Mgr Number ");

while(rs.next()) {out.print("<TR><TD ALIGN=CENTER>" + rs.getString("EMPNO"));out.print("<TD ALIGN=CENTER>" + rs.getString("LASTNAME"));out.print("<TD ALIGN=CENTER>" + rs.getString("DEPTNAME"));out.print("<TD ALIGN=CENTER>" + rs.getString("MGRNO"));

}

out.println("</TABLE>");}

Chapter 7. IBM Connection Manager 75

Page 100: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 55. doGet Method

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();try {

out.println("<HTML><HEAD><TITLE>ConnMgr Test</TITLE>");out.println("</HEAD><BODY>");executeSelect(out);releaseConnection();

} catch (SQLException sqlExcept) {out.println("<h1>---------- EXCEPTION IN SAMPLE CODE ----------</h1> <p>");out.println("Error:" + sqlExcept.getErrorCode());out.println("State:" + sqlExcept.getSQLState());sqlExcept.printStackTrace(out);out.println("<HTML><BODY>");

} catch (IBMConnMgrException mgrExcept) {if (out != null) {

out.println("<h1>--------- EXCEPTION IN SAMPLE CODE ----------</h1> <p>");out.println("<b>" + mgrExcept.getReason() + "</b>");out.println(mgrExcept);mgrExcept.printStackTrace(out);

} else {System.out.println("---------- EXCEPTION IN SAMPLE CODE ----------");System.out.println(mgrExcept);mgrExcept.printStackTrace();

}out.println("</BODY></HTML>");

}}

The code for the three databases mentioned below is the same, with theexception of the constants used to describe their database, connection pool,and driver name. To avoid repetition we will review all the methods forDB2 and will go through specifics of the other two databases.

Note

76 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 101: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2Before you start make sure your database is set up properly, see “DB2 UDBInstallation” on page 22 for more information.

The package in which the connection manager classes reside isibm.servlet.connmgr. The following is the class declaration for theUdbConnMgr class. It is here where the constants for the specific databaseand connection pool are specified (Figure 56).

Figure 56. UdbConnMgr Class Declaration

The getDriver method returns the JDBC driver name (Figure 57).

Figure 57. UdbConnMgr getDriver Method

The getPoolName method returns the pool name (Figure 58).

Figure 58. UdbConnMgr getPoolName Method

package itso.wasdb.connmgr

/** * This type was created in VisualAge. */ public class UdbConnMgr extends DbaseConnMgr{

private static final String DB2_POOLNAME="JdbcDb2";private static final String DB2_URL = "jdbc:db2:itsowdb";private static final String DB2_DRIVERNAME="COM.ibm.db2.jdbc.app.DB2Driver";

}

public String getDriver() {return DB2_DRIVERNAME;

}

public String getPoolName() {return DB2_POOLNAME;

}

Chapter 7. IBM Connection Manager 77

Page 102: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The getUrl method returns the URL (Figure 59).

Figure 59. UdbConnMgr getUrl Method

Sample OutputThe result of the run of this servlet is shown in Figure 60.

Figure 60. Connection Manager Output

public String getUrl() {return DB2_URL;

}

78 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 103: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

OracleBefore you start make sure your database is set up properly (see “Oracle 8Installation” on page 27).

The following is the class declaration for the OracleConnMgr class. Here iswhere the constants for the specific database and connection pool arespecified (Figure 61).

Figure 61. OracleConnMgr Class Declaration

The rest of the code is the same as that described in “DB2” on page 77. Theonly difference is that, inside the code, the DB2_ constants are replaced withthe ORACLE_ set of constants.

Microsoft SQL ServerBefore you start, make sure your database is set up properly (see “SQLServer Installation” on page 33).

The following is the class declaration for the SqlSrvConnMgr class. Here iswhere the constants for the specific database and connection pool arespecified (Figure 62).

Figure 62. SqlSrvConnMgr Class Declaration

The rest of the code is the same as that described in “DB2” on page 77. Theonly difference is that, inside the code, the DB2_ constants are replaced withSQLSRV_ set of constants.

/** * This type was created in VisualAge. */public class OracleConnMgr extends DbaseConnMgr {

private static final String ORACLE_POOLNAME = "JdbcOracle";private static final String ORACLE_URL = "jdbc:oracle:thin:@localhost:1521:orcl";private static final String ORACLE_DRIVERNAME = "oracle.jdbc.driver.OracleDriver";

}

/** * This type was created in VisualAge. */public class SqlSrvConnMgr extends DbaseConnMgr {

private static final String SQLSRV_POOLNAME = "JdbcSqlserver";private static final String SQLSRV_URL = "jdbc:odbc:SqlServer";private static final String SQLSRV_DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";

}

Chapter 7. IBM Connection Manager 79

Page 104: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

80 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 105: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

8 Data Access Beans:VisualAge for JavaIn this chapter we describe the IBM data access beans and their usagethrough WebSphere. For more detailed reading, refer to VisualAge for JavaEnterprise Version 2: Data Access Beans - Servlets - CICS Connector,SG24-5265.

Data access beans provide access to relational data. Using data access beansis the fastest, non-programming way of building SQL queries accessingexisting databases. Just open the Visual Composition Editor, place a Selectbean on the free-form surface, specify the database connection and data yourequire, and you are ready.

Most functionality is predefined. For example, your application can add,update, and delete rows, commit or rollback database transactions, handlemultiple connections, lock rows, make the access read only, and specify howmany rows are fetched into memory (cache).

An SQL Assist SmartGuide helps you to visually specify the data you need.You can select one or more tables, join tables, define search conditions,restrict the number of columns, sort the result set, and change the mappingbetween the SQL types in the database and the Java types in the application.

© Copyright IBM Corp. 1999 81

Page 106: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

In addition, an SQL Editor lets you enter SQL statements manually. Use thismethod when you need to compose very special or very sophisticateddatabase queries.1

After you have defined your database access using a Select bean, you canplace a DBNavigator bean into your visual application. The DBNavigatorbean incorporates buttons that navigate the result set of a query and performvarious relational database operations.

The Select bean fits into the JTable model of the new Java FoundationClasses (JFC, called Swing). This relationship between retrieved SQL dataand the Swing table model makes it very easy to develop attractive userinterfaces for Java applets and applications, based on standard Java classes.

With data access beans you have direct access to any database for which aJDK 1.1 compliant JDBC driver exists, for example, DB2 Universal Database(UDB) Version 5.2 Alternatively, you can use an ODBC driver together withthe JDBC ODBC bridge that comes with the Sun JDK.

Loading the Data Access Bean FeatureBefore you can use data access beans you have to add the data access beanfeature to the Workbench. Use the Quick Start menu (F2), select Features ->Add feature, and select IBM Data Access Beans 1.0 in the dialog that isdisplayed. This action loads the project into the Workbench and adds thedata access beans to the beans palette of the Visual Composition Editor.

Data Access Beans and the Standard SQL ClassesWhen using java.sql.* set of classes, you are required to write all of the SQLcode which sometimes can be a headache. Data access beans require less useof SQL and more Java. The following shows the similarities betweenjava.sql.* classes and data access beans (com.ibm.db.*) classes (Figure 63).

1 SQL Editor generated code, in contrast to SQL Assistant generated code, cannot handle SQL parameters (hostvariables) because the statement is not parsed. The developer or the application code can add the parameterdefinitions manually to the generated methods to enable passing of values into the host variables.2 You can also use DB2 V2.12, plus the latest CSD.

82 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 107: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 63. Data Access Beans Architecture

DatabaseConnection and java.sql.ConnectionDatabaseConnection is a replacement for java.sql.Connection. It provides thesame methods as its java.sql.Connection counter part. The connection can bemanaged internally or externally depending on which constructor is used.

Internal ConnectionThe DatabaseConnection default constructor provides a wrapping objectaround the JDBC connection for internal connection management. Theinternal management is rather simple. The connection that is created isshared by any application that makes a request to create a connection of thesame name; it can connect and disconnect from the database at any time.

With every request a counter gets incremented internally, and as objectsdisconnect, the counter is decremented. The object is released once thecounter is dropped back to 0 (Figure 64). This way multiple applicationsshare the same connection. Having this internal connection management isideal for query based applications.

If you are using an internal connection for update, you should be aware of allthe applications with access to the connection, because any application withthe connection can execute a commit or a rollback at any time. If you haveseveral beans with access to same connection you have to ensure thesequence of access to the connection to prevent any loss or duplication ofdata.

Data Access Beans Architecture

Connection

Statement

PreparedStatement

DatabaseConnection

ResultSet SelectResult

SelectStatement

com.ibm.db.*java.sql.*

Chapter 8. Data Access Beans: VisualAge for Java 83

Page 108: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 64. Internal Connection Management by DatabaseConnection

External ConnectionWhen using the DatabaseConnection (java.sql.Connection) constructor, theconnection is considered to be externally managed. You can get thisconnection object from some other externally managed connection pool, suchas IBM’s connection manager. You cannot issue the connect or disconnectmethods against an externally managed connection (Figure 65).

Figure 65. External Connection Management by IBM ConnectionManager

DatabaseConnection

java.sql.Connectionconn

ApplicationApplicationApplication

BA C

Once all three applicationsdisconnect() the object connis closed.

DatabaseConnection

java.sql.ConnectionconnA

DatabaseConnection

java.sql.ConnectionconnB

DatabaseConnection

java.sql.ConnectionconnC

JdbcDb2 JdbcOracle

ConnectionManager

DB2 Oracle

84 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 109: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Statement TypesThe class com.ibm.db.SelectStatement represents an SQL select statement,which is roughly equivalent to both java.sql.Statement andjava.sql.PreparedStatement classes. The SelectStatement always works witha helper object; an instance of com.ibm.db.StatementMetaData.

Figure 66 shows the way in which these objects are constructed. ASelectStatement holds a StatementMetaData. A StatementMetaData iscomposed of SQL query text and column information. Note that multipleSelectStatements can share the same StatementMetaData, the information isread only from that perspective.

Figure 66. Select Statement Design

ResultSet TypesThere are certain drawbacks in using JDBC directly; the java.sql.ResultSetcan only scroll forward, not backward. The com.ibm.db.SelectResult class ofthe data access beans is traversable both backward and forwards, and it alsoallows jumping to a particular index. The SelectResult is already positionedat the first row.

The SelectResult reads the content of ResultSet into its structure. TheSelectResult has the performance hit the first time it does that. Theadvantage of the SelectResult becomes apparent when there is a need toscroll up and down the ResultSet several times.

SelectStatement

StatementMetaData

SQL Query Text

Column Typing Information

Chapter 8. Data Access Beans: VisualAge for Java 85

Page 110: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Building a Servlet using Data Access BeansWe chose to use the Servlet Builder in VisualAge for Java to create oursamples. There are three samples in which each of them accesses a differentDBMS: DB2, Oracle and SQL Server.

When describing the examples we avoided one-by-one steps involved increating the servlet because there is a book dedicated to that topic. Pleaserefer to VisualAge for Java Enterprise Version 2: Data Access Beans - Servlets- CICS Connector, SG24-5265, for details about visual servlet construction.

Sample Data Access BeansIn this sample the servlet takes a department number, and using a Selectbean, it executes a query against the employee table and returns the list ofemployees into a list box. It also displays the number of employees within thedepartment. For detailed information on the database tables structure,please refer to “Relational Database Installation and Setup” on page 21.

Every database system has its own servlet class and Select bean. The servletcontains basic information on the parameters of the servlet, such as thedepartment number entry field. The Select bean contains all of theinformation on the type of database, DB2, Oracle, or SQL Server, the tablesinvolved, and the type of the query. No line of code is written to create thisservlet. All of the code is generated by VisualAge for Java. All of theinformation on the tables and the beans is stored through a sequence ofpanels and dialogs, as part of the visual composition.

Creating a Servlet Visually using Data Access BeansTo create a servlet visually using data access beans, we create the visualservlet, tailor a Select bean for database access, and then construct the logicthrough connections in the visual composition.

Visual ServletTo create the visual servlet follow these steps:

❑ Create the new servlet class UdbDabServlet in the itso.wasdb.accessbeanpackage using Quick Start from the menu (F2). Use the servlet palette inthe visual composition editor to design the HTML output page of theservlet. In our example we use the same HTML page for input and output(Figure 67).

86 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 111: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 67. Servlet User Interface

❑ Notice the naming of these beans:

• The HtmlEntryField is named deptnum

• The HtmlText ...deptnum... is named deptresult

• The HtmlText ...number...is named numemp

• The Retrieve push button is named retrieveButton

❑ Save the servlet. This generates the underlying Java code. In particularthis creates a JavaBean (UdbDabServletFormData) that holds all thedata of the data entry form, that is, the department number (deptnum)and the Retrieve push button.

❑ From the Servlet palette (Figure 68) select the FormData bean and choosethe UdbDabServletFormData as the class name in the dialog. This classwas generated in the step before. Place it somewhere outside the userinterface of the servlet. This bean represents the actual data input whichcan be done in the user interface. In our example, this bean contains as aproperty named deptnum the department value entered in theHtmlEntryField.

HtmlText

HtmlForm

HtmlButton

HtmlTable

HtmlResultTable

HtmlForm

HtmlEntryField(deptnum)

Chapter 8. Data Access Beans: VisualAge for Java 87

Page 112: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 68. The Servlet Palette

❑ From the Database palette drag and drop a Select bean and name itUdbEmpInDept (Figure 69).

Figure 69. Servlet with Data Access Bean and Select Bean

Select BeanTo tailor the database access you open the Select bean to specify the databaseconnection and SQL statement.

❑ Double click on the UdbEmpInDept bean. Select the query field and clickon the grey box. Now you can set up a database connection and an SQLstatement (Figure 70).

88 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 113: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 70. UdbEmpInDept Connection Setup

❑ Click on the New button to create a new database access class(UdbDabAccess) that will hold the connection information and the SQLstatement to be executed.

❑ Click on the Add button to add a connection to a database (Figure 71).Specify the URL, the driver, the user ID, and the password. The name ofthe connection (connect) then becomes a method name in the databaseaccess class.

By defining multiple connections it is possible to access differentdatabases, or the same database with different user IDs (and differentrights) just by choosing another connection method.

Chapter 8. Data Access Beans: VisualAge for Java 89

Page 114: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 71. Connection Alias Setup

❑ Test the connection (the DBMS must be up and running) and only proceedif you get a successful answer.

❑ Click OK to generate the connect method into the database access class.

❑ Select the SQL tab to set up an SQL query (Figure 72).

Figure 72. UdbEmpInDept SQL Setup

90 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 115: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Click on the Add button and input the SQL Name in the SQLSpecification panel (Figure 73). This name becomes the name of themethod that is generated into the database access class.

Figure 73. Creating New SQL Specification

In most cases, you will select the Use SQL Assist SmartGuide radiobutton. The SQL Assist SmartGuide enables you to build an SQLstatement without much knowledge of SQL. You go through a set of pagesto specify the tables, columns, and conditions of your SQL access.

❑ On the Tables page select the table(s) (Figure 74).

Figure 74. Selecting a Table for the Query

Chapter 8. Data Access Beans: VisualAge for Java 91

Page 116: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ On the Condition 1 page you can create a WHERE clause with columnspecifications. To pass a variable as a value enter the name of a hostvariable (:DEPTNUM ) that will be set at execution time (Figure 75). Youwill recognize that if you enter a host variable beginning with a colon thename is printed in uppercase bold letters.

Figure 75. Setting Query Condition(s)

❑ On the Columns page select the columns to be retrieved (Figure 76).

92 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 117: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 76. Selecting Columns to Include for a Query

❑ On the Sort page optionally select the columns used to sort the resultingrows. This creates an ORDER BY clause in the SQL statement.

❑ On the Mapping page you can perform simple conversions of SQL datatypes for your Java program, for example, converting numeric data toappropriate Java data types.

❑ The SQL page displays the resulting query statement from the choicesmade in previous pages (Figure 77).

Chapter 8. Data Access Beans: VisualAge for Java 93

Page 118: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 77. SQL Query Statement

❑ You can test the SQL statement by clicking on the Run SQL button. Youare prompted for the host variable value, the SQL statement is executed,and the results are displayed in a table.

❑ Click on Finish to generate the code. The SQL statement is added to thequery (Figure 78).

94 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 119: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 78. Resulting SQL Query

Up to this point, the setup for the servlet and the Select bean have beendescribed.

DBMS Selection

This example was developed using the DB2 DBMS. To develop a servlet thatuses another database, the same steps apply, except for the connectionparameters. A different connection alias, appropriate for that databasesystem, has to be provided (Figure 71 on page 90).

We developed the same sample also for Oracle (OrclDabServlet) and SQLServer (SqlSrvDabServlet).

Logic ConnectionsFigure 79 shows the final servlet after all the proper connections have beenestablished between the objects and the user interface.

Follow these steps to create the connections:

1. Connect the retrieveButtonPressed event of the UdbDabServletFormDatabean to the execute method of the UdbEmpInData bean.

Chapter 8. Data Access Beans: VisualAge for Java 95

Page 120: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

2. Connect the deptnumString property of UdbDabServletFormData1 to theParm_DEPTNUM_String property of UdbEmpInDept.

3. Connect the deptnumString property of UdbDabServletFormData1 to thestring property of the ...deptnum... HtmlText bean.

4. Connect the this property of the UdbEmpInDept Select bean to thetableModel property of the HtmlResultTable.

5. Connect the executed event of the UdbEmpInDept to the string property ofthe ...number... HtmlText. The result line is still dashed, meaning that aparameter is missing.

6. Connect the value parameter of the previous connection to the numRowsproperty of UdbEmpInDept.

Figure 79. UDB Servlet Using Data Access Beans: Visual Composition

At this point you can generate the code and run it.

Tailoring the Output Result TableBy default the HTMLResultTable bean displays the long columns names,which, depending on the database, consist of the schema name, the tablename, and the column name.

We modified the empindept method of the UdbDabAccess class to specifyshort column names (Figure 80).

1 2

3

4

5 6

96 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 121: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 80. Tailored Method with Short Columns Names

Running the ServletFigure 81 shows the result of the servlet in a Web browser. Start theWebSphere Test Environment (SERunner class), then enter the URL:

http://127.0.0.1:8080/servlet/itso.wasdb.accessbean.UdbDabServlet

Figure 81. Output Result of the Servlet in a Web Browser

Before: aSpec.addColumn("EMPLOYEE.EMPNO", 1,1);aSpec.addColumn("EMPLOYEE.FIRSTNME", 12,12);aSpec.addColumn("EMPLOYEE.LASTNAME", 12,12);aSpec.addColumn("EMPLOYEE.JOB", 1,1);aSpec.addColumn("EMPLOYEE.SEX", 1,1);aSpec.addColumn("EMPLOYEE.BIRTHDATE", 91,91);

After: aSpec.addColumn("EMPNO", 1,1);aSpec.addColumn("FIRSTNME", 12,12);aSpec.addColumn("LASTNAME", 12,12);aSpec.addColumn("JOB", 1,1);aSpec.addColumn("SEX", 1,1);aSpec.addColumn("BIRTHDATE", 91,91);

Chapter 8. Data Access Beans: VisualAge for Java 97

Page 122: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Using the Connection Manager and Data Access BeansIn this section we develop an example servlet that uses both the connectionmanager to establish and manage the connections to the database systemand a non-visual data access bean.

The servlet function is to search for a record in the employee table, anddisplay and update the record.

Class DefinitionThe first step is the class definition in a new itso.wasdb.connaccess package(Figure 82). We coded the database access for all three DBMSs, however, twoare in comments.

Figure 82. EmployeeServlet Class Declaration

package itso.wasdb.connaccess;

import com.ibm.servlet.connmgr.*;import com.ibm.db.*;import java.sql.*;import java.io.PrintWriter;import javax.servlet.*;import javax.servlet.http.*;

public class EmployeeServlet extends javax.servlet.http.HttpServlet {com.ibm.servlet.connmgr.IBMConnSpec connSpec = null;static com.ibm.servlet.connmgr.IBMConnMgr connMgr = null;

final static String POOLNAME = "JdbcDb2";final static String URL = "jdbc:db2:itsowdb";final static String DRIVERNAME = "COM.ibm.db2.jdbc.app.DB2Driver";/*final static String POOLNAME = "JdbcOracle";final static String URL = "jdbc:oracle:thin:@localhost:1521:orcl";final static String DRIVERNAME = "oracle.jdbc.driver.OracleDriver";

final static String POOLNAME = "JdbcSqlserver";final static String URL = "jdbc:odbc:SqlServer";final static String DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";*/

final static String USER = "itso";final static String PASSWORD = "itso";final static String SELECT = "SELECT EMPNO, FIRSTNME, LASTNAME, JOB, SEX FROM ITSO.EMPLOYEE

WHERE LASTNAME = :LNAME"; StatementMetaData metaData = null;

98 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 123: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The class declaration has nothing really fancy in it. As most servlets it isderived from HttpServlet, it defines the connection parameters, the user IDand the password. This can be easily changed, or even better, the servletmight read this from a property file. In the last line a StatementMetaDataObject is declared. This object will contain all information for the query andin the same turn also for the update of the database.

InitializationThe next part is the init method. The main purpose of this method is toinitialize the connection manager and to create the StatementMetaDataobject (Figure 83).

Figure 83. EmployeeServlet init Method

public void init(ServletConfig config) throws ServletException {super.init(config);// Specify the connection, now for simplicity this is hardcoded// It would be nicer to read this from a property fileconnSpec = new IBMJdbcConnSpec(POOLNAME,

true, DRIVERNAME, URL, USER, PASSWORD);

// Now get the static instance of the Connection Manager// from the Utility Class if not already doneif (connMgr == null)

connMgr = IBMConnMgrUtil.getIBMConnMgr();

// Next step is to prepare the Statement which will be run// agains the database. Therfor create the MetaData ObjectmetaData = new StatementMetaData();// Spefify the select statement for the metaData's SQL statmentmetaData.setSQL(SELECT);try{

// Define the input parameter with the type of class we use// for input (String) and the the SQL source type (CHAR)metaData.addParameter("LNAME", String.class, Types.VARCHAR);// Next define all ouput parameter in the same waymetaData.addColumn("EMPNO", String.class, Types.CHAR);metaData.addColumn("FIRSTNME", String.class, Types.VARCHAR);metaData.addColumn("LASTNAME", String.class, Types.VARCHAR);metaData.addColumn("JOB", String.class, Types.CHAR);metaData.addColumn("SEX", String.class, Types.CHAR);// Define the table name which is used in the querymetaData.addTable("ITSO.EMPLOYEE");

} catch (DataException e) {System.out.println("Error: " + e.toString());throw new ServletException(e.toString());

}}

Chapter 8. Data Access Beans: VisualAge for Java 99

Page 124: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

In the first part a new database connection is specified. The connectionconsists of the constants we saw already in Figure 82. Afterwards a newstatic reference to the connection manager is created, if not already there.

In the second part a new StatementMetaData object is created. The SQLselect statement (see Figure 82) is then passed to this object. Notice the lastpart of the SELECT statement:

".... WHERE LASTNAME = :LNAME"

This variable LNAME will be later replaced by an actual value. To do this,LNAME has to be specified as an input parameter, which is done in the nextline. Moreover, it also specifies the Java class that will be used to specify thisparameter, and what the resulting SQL type is. If you observe any problemshere refer to “Data Access Beans” on page 266.

The next lines are quite similar except that now the output columns arespecified. The arguments are the SQL column name, the Java class that isused to represent this value, and the according SQL type. We will see laterthat it is useful to provide this information to allow a convenient access to theresult set and, moreover, it is a nice way to update a row.

The last line specifies the SQL table that contains all the given columns.

Form Parameter AccessThe getParameter method is a helper method (Figure 84).

Figure 84. EmployeeServlet getParameter Method

This method is handy to retrieve the parameter given to a servlet in therequest. It just returns the first value for a key from the request object givento the servlet. For example, if the HTTP request is:

http://myserver/Servlet?firstName=Tobias&lastName=Himstedt&firstName=Amir

then getParameter(request, "firstName") would return "Tobias".

public String getParameter(HttpServletRequest request, String key) {String values[] = request.getParameterValues(key);if (values != null)

return values[0];return null;

}

100 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 125: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Form ProcessingThe next thing to is to define doGet and doPost. Because they should do thesame, we call the same performTask method so that we are free to use eitherHTTP-POST or HTTP-GET. The servlet works with both options (Figure 85).

Figure 85. EmployeeServlet doGet and doPost Methods

Both methods call the performTask method, which itself is also very simple.Depending on the request, it either calls the method to retrieve the data foran employee or to update the data (Figure 86).

Figure 86. EmployeeServlet performTask Method

Based on the value for the command parameter in the HttpServletRequestobject, performTask either calls getEmployee to fetch a specific row from theemployee table or updateEmployee to update an already fetched row.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

performTask(request, response);}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

performTask(request, response);}

public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

String command = getParameter(request, "command");

if ( command == null || command.equals("getEmployee") )getEmployee(request, response);

else if (command.equals("updateEmployee"))updateEmployee(request, response);

}

Chapter 8. Data Access Beans: VisualAge for Java 101

Page 126: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Employee RetrievalThe getEmployee method processes the retrieval of an employee (Figure 87).

Figure 87. EmployeeServlet getEmployee Method (I)

What is happening so far is not very exciting. Basically, the response isspecified, the caching is disabled, the output PrintWriter is created from theresponse object, and the parameter for the database query is detected. Nextthe beginning of the result page is printed to the PrintWriter.

The next part retrieves a connection to the database based on thespecification made in the init method (see Figure 83) from the connectionmanager. From this connection a JDBC connection is created. This is used tocreate a DatabaseConnection used for the data access beans (Figure 88).

Figure 88. EmployeeServlet getEmployee Method (II)

The next part is about how to use the DatabaseConnection object to create aSelectStatement based on the SelectMetaData initialized in the init method(Figure 89).

public void getEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

IBMJdbcConn conn = null;Connection jdbcConn = null;SelectResult resultSet = null;

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);

// Get the output writerPrintWriter out = response.getWriter();

// Get the lastName paramenter for queryString queryName = getParameter(request, "lastName");

out.println("<HTML><HEAD><TITLE>ConnMgr / DataAccess</TITLE></HEAD><BODY>");

try {// Get the connection from the connection managers poolconn = (IBMJdbcConn) connMgr.getIBMConnection(connSpec);// Get the JDBC connection objectjdbcConn = conn.getJdbcConnection();// Now use this JDBC connection for the creating// a connection usable by the data access beansDatabaseConnection dataConnection = new DatabaseConnection(jdbcConn);

102 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 127: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

To execute the query against the database the query has to be completed withthe actual query value. The value is retrieved from the servlet request(Figure 87 on page 102) and is then passed as parameter LNAME to thequery. Now the query is ready to execute. After execution the resultSet isretrieved.

Figure 89. getEmployee Method (III)

In Figure 90 the values for the columns are retrieved. Based on the columnvalues the HTML output is generated as a table with a form in it. Thisenables the user to enter values for all the fields except for the primary key.

Figure 90. EmployeeServlet getEmployee Method (IV)

SelectStatement select = new SelectStatement();select.setConnection(dataConnection);select.setMetaData(metaData);

select.setParameter("LNAME", queryName);

select.execute();

resultSet = select.getResult();

String empNo = resultSet.getColumnValueToString("EMPNO");String firstName = resultSet.getColumnValueToString("FIRSTNME");String lastName = resultSet.getColumnValueToString("LASTNAME");String job = resultSet.getColumnValueToString("JOB");String sex = resultSet.getColumnValueToString("SEX");out.println("<TABLE>" +

"<FORM ACTION = \"/servlet/itso.wasdb.connaccess.EmployeeServlet\">");out.println("<TR>");out.println("<TH>Emp Number");out.println("<TH>First Name");out.println("<TH>Last Name");out.println("<TH>Job");out.println("<TH>Sex");

out.println("<TR><TD>" + empNo);out.println(" <TD><INPUT TYPE=TEXT NAME=firstName VALUE=\"" +

firstName.trim() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=lastName VALUE=\"" +

lastName.trim() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=job VALUE=\"" +

job.trim() + "\">");out.println(" <TD><INPUT TYPE=TEXT SIZE=1 NAME=sex VALUE=\"" +

sex.trim() + "\">");

out.println("<TR><TD><INPUT TYPE=HIDDEN NAME=command VALUE=updateEmployee>");out.println("<TD><INPUT VALUE=Update TYPE=SUBMIT>");out.println("</FORM></TABLE>");

Chapter 8. Data Access Beans: VisualAge for Java 103

Page 128: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Notice the action attribute of the FORM tag. It points back to the sameservlet. In the source code this might look a bit wild, but as HTML output inthe browser, it is straightforward and is shown in Figure 91.

Figure 91. Output of the getEmployee Method

Continuing with the servlet code we have one more important thing to do. Westore the resultSet in a session object associated with the servlet request.This enables us later to use this resultSet to update the row (Figure 92).

Figure 92. EmployeeServlet getEmployee Method (V)

The last part contains the error handling statements (Figure 93).

Figure 93. EmployeeServlet getEmployee Method (VI)

HttpSession session = request.getSession(true);session.putValue("itso.wasdb.connaccess.Employee.resultSet",

resultSet);

} catch (IBMConnMgrException e) {System.err.println("Error: " + e.toString());e.printStackTrace(out);

} catch (DataException e) {System.err.println("Error: " + e.toString());out.println("<H2>Error: " + e.toString() + "</H2>");e.printStackTrace(out);

}out.println("</BODY></HTML>");

}

104 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 129: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Employee UpdateAfter retrieving an employee, the user can update the column values. TheupdateEmployee method performs the processing. The method begins withsome administrative code (Figure 94).

Figure 94. EmployeeServlet updateEmployee Method (I)

In Figure 95 the session we created (see Figure 92) is now retrieved from theservlet request. In this session we have stored the resultSet of the query.

Figure 95. EmployeeServlet updateEmployee Method (II)

Next we retrieve the values from the input fields (Figure 96).

Figure 96. EmployeeServlet updateEmployee Method (III)

Now we are ready to perform the update (Figure 97). If the values weregiven, they are passed to the resultSet of the query retrieved by thegetEmployee Method. Finally the row is updated and closed; also theconnection manager is informed that the connection is released.

SelectResult resultSet = null;

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);

// Get the output writerPrintWriter out = response.getWriter();

out.println("<HTML><HEAD><TITLE>Result</TITLE></HEAD><BODY>");

HttpSession session = request.getSession(false);resultSet = (SelectResult)

session.getValue("itso.wasdb.connaccess.Employee.resultSet");

String lastName = getParameter(request, "lastName");String firstName = getParameter(request, "firstName");String job = getParameter(request, "job");String sex = getParameter(request, "sex");

Chapter 8. Data Access Beans: VisualAge for Java 105

Page 130: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 97. EmployeeServlet updateEmployee Method (IV)

The last part contains the error handling statements (Figure 98).

Figure 98. EmployeeServlet updateEmployee Method (IV)

Testing the ServletTo test the servlet you may want to use to WebSphere Test Environmentprovided by VisualAge for Java (start the SERunner class).

Open a browser and enter the URL:

http://127.0.0.1:8080/servlet/itso.wasdb.connaccess.EmployeeServlet?lastName=LEE

Alternatively you can launch the servlet from VisualAge for Java. Beforelaunching the servlet, you can setup the query parameter (host variable) inthe servlet properties so that an employee is found in the table.

From the context menu of EmployeeServlet select Tools -> Servlet Launcher-> Properties to display the servlet launcher properties dialog and enter thevalues shown in Figure 99.

try {if (lastName != null)

resultSet.setColumnValue("LASTNAME", lastName);if (firstName != null)

resultSet.setColumnValue("FIRSTNME", firstName);if (job != null)

resultSet.setColumnValue("JOB", job);if (sex != null)

resultSet.setColumnValue("SEX", sex);

resultSet.updateRow();resultSet.close();conn.releaseIBMConnection();

} catch (DataException e) {System.err.println("Error: " + e.toString());out.println("<H2>Error: " + e.toString() + "</H2>");e.printStackTrace(out);

}out.println("<H1>Update successfull</H2>");out.println("</BODY></HTML>");

}

106 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 131: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 99. Properties for the Employee Servlet

After launching the servlet the browser should appear as shown in Figure 91on page 104. You may then enter the text fields to update the database. If theupdate was successful, the servlet will let you know with a message.

Deploying Servlets to WebSphereFor detailed instructions on deploying servlets to WebSphere, see chapter 20of the IBM redbook VisualAge for Java Enterprise Version 2: PersistenceBuilder with GUIs, Servlets, and Java Servlet Pages, SG24-5426.

An example of deployment of a servlet to WebSphere is described in“Deploying a Servlet to WebSphere” on page 128. Make sure that thec:\IBMVJava\eab\runtime20\ivjdab.jar file is part of the WebSphere class path.

Chapter 8. Data Access Beans: VisualAge for Java 107

Page 132: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

108 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 133: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

9 Persistence Builder:VisualAge for JavaIn this chapter we discuss the use of relational databases to providepersistence for Java objects. We will use the VisualAge for Java PersistenceBuilder tool to create persistent classes based upon existing database tables.We will use our ITSOWDB database as described in Chapter 4, “RelationalDatabase Installation and Setup” on page 21.

For these examples, the Persistence Builder tool must be added to yourworkspace. You can add the feature from File -> Quick Start -> Features ->Add Feature -> Enterprise Access Builder for Persistence.

If you have already added the WebSphere Test Environment feature, thePersistence Builder feature will report an error when the feature is added.As the error message indicates you must remove the Websphere Testenvironment feature, then add the Enterprise Access Builder forPersistence feature again. This will also install the WebSphere TestEnvironment for you.

Notice

© Copyright IBM Corp. 1999 109

Page 134: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

What is Persistence?In Java, as with all programming languages, the state of an object is lostwhen the object finishes execution, unless the state of the object isexternalized before execution is complete. This is true for any informationwhich a program utilizes. In Java, saving the state, or any information,before program completion and restoring the state, or retrieving information,when the object is instantiated again, is known as persistence.

Java persistence can be achieved by serializing an object. That meansconverting the object’s state into a sequence of bytes, then storing the bytes,which can later be read to resurrect the original object. This way an objectdoes not need to know how to access a file to retrieve data itself; instead,whoever calls the object resurrects the entire object, including any data andthe object state.

Using Databases to Provide PersistenceDatabases can also be used to provide persistence for Java objects. Theobject’s state can be stored in a traditional SQL database and thenresurrected by querying the database. The Persistence Builder is a VisualAgefor Java tool which guides you through the creation of classes that providepersistence functionality.

Although the tool can be used to create persistent objects from scratch, one ofPersistence Builder’s most powerful abilities is to take an existing databaseand create a persistent Java application using the existing design of thatdatabase. The tool includes all of the relations between tables and databaserules in its design. It creates object definitions based on your tables, whichcan be used in your Java applications.

Persistence Builder ToolsFor detailed instructions on using the Persistence Builder, review theredbook VisualAge for Java Enterprise 2: Persistence Builder with GUIs,Servlets, and Java Server Pages, SG24-5426.

The tool has three major components used to define how the tool will createyour Java code for implementing object persistence. The Schema, Model, andMapping Browsers enable you to define the table model, the object model,and the mapping between the two models.

110 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 135: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Schema BrowserThe Schema Browser is used to import, create, view, and modify therelationships between the actual tables in your database. This browser iswhere the Persistence Builder gathers the necessary information (forexample, column definitions, foreign key relationships) from your database tocreate objects based on the data stored within. Using your newly createdschema, a model can be generated based on the schema.

Model BrowserThe Model Browser creates the actual persistent classes whose data will beexternalized. It adds to these objects attributes and associations from theschema. It is important that the schema truly represents your physicaldatabase to ensure that the objects can interact correctly with the actualdatabase. In our example the objects will be employee and department.

Map BrowserThe Map Browser is used to control mappings between the tables and themodel classes. It is used to map the object attributes and associations to theactual database tables.

Vendor Specific ConsiderationsAs this book was written, the released version of VisualAge for JavaPersistence Builder only supported the importing of DB2 databases to createa persistent application’s schema.

A fix for importing Oracle and SQL Server databases to create a schema waswritten as this book went to publishing. The fix requires a package to beimported and a file to be placed in your VisualAge for Java directory. Withthis fix, you can import the Oracle or SQL Server database and create theproper schema.

If your version of VisualAge for Java fails to import these schemas, contactVisualAge for Java support for the proper fixes.

Chapter 9. Persistence Builder: VisualAge for Java 111

Page 136: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Persistence Builder Example: Employees in DepartmentWe will attempt to take an existing database from DB2, Oracle, and SQLServer to create a simple persistent object model. Then we will create aservlet that uses this model. The servlet takes a department number as inputand returns a list of employees within that department. The first step is tocreate a schema for your objects based on your table.

Import the SchemaFrom your Workbench, open the Schema Browser by selecting Workspace ->Tools -> Persistence Builder Tools -> Browse Schema. Since we want to createour schema from an existing database, we use the import function. This typeof design is also known as a bottom-up design because we are starting with adatabase and building our application around it. Select Schema -> Import /Export Schema -> Import Schema from Database. Now enter the name youwish to call your schema; in our example, we call the schema ITSO.

You must now enter the JDBC connection information (Figure 100). Thisconnection information is dependent on the database vendor you are using asa datastore. The connection and driver specifications used here should relateto the information used to create a connection in Chapter 5, “Java DatabaseConnectivity” on page 43.

Figure 100. Importing a Schema

112 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 137: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Once the connection is established, you select the tables you want to importfrom. Each table you want to import must be highlighted (use the shift keywith the mouse for multiple selections) as in Figure 101.

Figure 101. Import Table Selection

The Persistence Builder now generates the schema from the database anddisplays it in the Schema Browser (Figure 102).

The schema is a representation of your actual database. You should look ateach column’s attribute by double clicking on the attribute and confirm thatit is the correct type (Figure 103).

It is also a good idea to inspect the foreign key relationships. It is importantthat all foreign keys from the table are displayed in the schema. If arelationship is not shown, create one based on the physical table in thedatabase, otherwise the correct classes will not be created later on.

We renamed the foreign key relationship to depts (Figure 102). When theschema is generated from your database, if the foreign key relationship is notgiven a name in your SQL statements, the schema browser uses the internalrestraint name used by your database. To rename a relationship, use therelationship’s context menu and select Rename Foreign Key Relationship.

Chapter 9. Persistence Builder: VisualAge for Java 113

Page 138: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 102. Schema Browser

Figure 103. Schema Column Editor

114 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 139: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Generate and Validate the Object ModelThe next step is to generate the model from the schema. Select Schemas ->Generate Model from Schema. The Persistence Builder builds a model of theobjects based on the database schema. You should now open the ModelBrowser. You can open it either from the tools menu from the Workbench asdescribed earlier, or from the schema window, select Persistence Builder Tools-> Model Browser.

The Model Browser (Figure 104) is a view of the object model; instead oftables and columns it has classes and attributes.

Figure 104. Model Browser

Not all of the column specification from the schema transfers to the objectmodel. It is important to inspect the classes, attributes, and keys as well.

Notice that the NOT NULL option of columns in the tables does not cause theValue required checkbox to be marked. You should open all of the attributesthat map to columns that are not null (by double clicking on the classattribute to edit) and checking the Value required checkbox (Figure 105).

Chapter 9. Persistence Builder: VisualAge for Java 115

Page 140: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 105. Attribute Editor: Marking the Value Required Field

Inspect the MapOpen the Map Browser (under Persistence Tools) to inspect the mappingfrom the schema to the model. If the model objects do not map properly to thephysical database, the map browser will inform you. The map was createdwhen you generated the model from the schema. It is important that themapping is correct before you attempt to generate the Java code, or some ofthe generated Java methods will not function properly. In the Map Browserselect the generated DataStore Map, in this example ITSOItso.

In Figure 106 we see a broken table mapping. In this particular example wesee an error converting the type of the table column to the class attribute. Ifyou open the table in the Schema Browser, we see that Employee.hiredatehas a type TIMESTAMP. If you then look in the Model Browser, the hiredateattribute has a type DATE.

116 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 141: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 106. Map Browser with a Broken Table Map

We have two ways of fixing this mapping problem: we can change themapping function by double clicking on the attribute in error, or change thetype of one of the attributes in conflict. We chose to change the type of thehiredate attribute in the Model Browser to a type of java.sql.Timestamp. Theerror displayed in the Map Browser is then cleared as in Figure 107.

Figure 107. Model Browser

If you have found any errors or made any changes in the Schema Browser,remember to regenerate the model based on the new schema.

Chapter 9. Persistence Builder: VisualAge for Java 117

Page 142: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Generate the Java Code for the Object ModelNow that the three browsers correctly define how you want your objects tobehave, it is time to generate the actual code. From your Model Browser,select Models -> Generate. Three options are presented in the SmartGuide(Figure 108).

Figure 108. Generation Options

The first step is to generate the Java classes and interfaces of the objectmodel, which is the first radio button. The next panel prompts you for theproject and package names. For our example, we used the itso.wasdb.persistpackage.

As shown in Figure 109, you should mark the Generate Bound BeansProperties checkbox. Model classes with bound properties firepropertyChange events, which is useful when creating applications usingvisual construction.

118 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 143: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 109. Generation Options (Bean Properties)

The next panel asks you which model elements you would like to generate;for our example, all of the elements. Click on the Finish button and theclasses are generated.

Generate the Java Code for the Service ClassesNow that the object classes have been defined, it is necessary to generate theservice classes that will handle the persistent aspect of your objects. Theservice classes are responsible for externalizing all of the information in yourobjects and later resurrecting those objects.

From the Model Browser, select Models -> Generate. This time you will selectthe second radio button displayed in Figure 108 on page 118, Data ServiceClasses and Interfaces. The next panel prompts you for the type of schema togenerate. We are using the existing relational database to store theinformation, therefore we select the third radio button, Relational SQL

Chapter 9. Persistence Builder: VisualAge for Java 119

Page 144: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

(Figure 110). Enter the package name for the service classes, in our caseitso.wasdb.persist.Services.

Figure 110. Schema Generation Selection

After completing this panel, select Next to display the database connectioninformation prompt. Enter the correct information to connect to the database(same as in Figure 100 on page 112) and then select the Generate queriesusing parm marker bindings checkbox (Figure 111).

120 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 145: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 111. Database Connection Information

Next you will be prompted for the model elements to include, in our case allelements and then click on Finish. If you look in the Workbench, you will seethat your packages have been successfully created.

You are now ready to build a persistent application, but first, save the model,schema, and map definitions in the itso.wasdb.persist.metadata package (usethe File menu in each browser).

Build the ServletNow that all the classes are in place, you can create a visual servlet tointeract with the persistent objects. From the Workbench, select File -> QuickStart -> Servlets -> Visual Servlet. You are prompted for the project, package,and name of servlet. Use a naming convention you feel comfortable with. Weused the itso.wasdb.persist.gui package and we named the servletEmpsInDept and selected a simple model to work with.

Chapter 9. Persistence Builder: VisualAge for Java 121

Page 146: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The next panel asks you the name of the servlet to use for the Action form; weused the same servlet name. Click on Finish and the SmartGuide creates theclasses and opens the visual composition editor. We will not go into depthconcerning the use of the visual composition editor, instead we display someof the steps and the resulting design.

Visual Layout of the HTML Output PageWe first have to create the HTML output page itself. In Figure 112, we havecreated the form to enter the department name. There are a few HtmlTextbeans, an HtmlEntryField that we named DeptEntryField, and aHtmlPushButton named DeptSubmitButton. The prompt, entry field, andbutton are within a three column, single row table. At the bottom we useanother form with an HtmlResultTable named EmpListResult. Save thedesign so that the FormData bean is generated.

The composition of the servlet is very similar to the one given in “Creating aServlet Visually using Data Access Beans” on page 86.

Figure 112. HTML Output Page of a Servlet

122 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 147: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Beans for Data RetrievalNext we placed the beans required for the logic. We select the FormData beanfrom the palette and select the EmpsInDeptFomdata that was generatedwhen saving the visual layout. This bean represents the HTML form and hasall the information and actions that can take place on the visual form.

Because we are entering a department number, we have to retrieve theactual department object for that number. If we want to find all employees ina department, we start with the department object and follow therelationship to get the employees. To retrieve the department object we use aand enter the DeptHomeBean class from the itso.wasdb.persist package.

Once that department object is found, it needs a place to be stored, thereforewe place a department object on the page as well. We use a transactedvariable of type DepartmentHomeImpl to represent the department retrievedthrough the home class.

We now switch to the Persistence Builder palette to add the objects we willneed to enact the persistence services. We select a read-only transaction beanbecause we are only reading information without any updates. We also use aVapDefaultRelationshipTableModel bean to convert the list of employees intoa displayable form. Both of these icons are in the palette (Figure 113).

Figure 113. Visual Composition Editor with Persistence Builder Palette

Chapter 9. Persistence Builder: VisualAge for Java 123

Page 148: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Connections for the LogicNow that we have all the necessary beans, we must add the connectionsbetween the objects (Figure 114).

Figure 114. Composition Editor with Connections

Connections:

1. Retrieve the department when the form is submitted:EmpsInDeptFormData(Event DeptSubmitButtonPressed) toDepartmentHome(find(java.lang.String) method)

2. Pass the department number entered to the find method:EmpsInDeptformData(property deptEntryFieldString) to parameter offind(deptno)

3. Store the result of the find method as a department object:NormalResult to DepartmentHomeImpl(this)

4. Set the current transaction for the department:ReadOnlyTransaction(this) to DepartmentHomeImpl(transaction)

5. Set the current transaction for the employee result:ReadOnlyTransaction(this) toVapDefaultRelationshipTableModel(transaction)

6. Retrieve the employees of the department:DepartmentHomeImpl(property employee) toVapDefaultRelationshipTableModel(relationship)

6

4

5

7

2

13

124 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 149: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

7. Display the employees of the department:VapDefaultRelationshipTableModel(this) toEmpListResultTable(tableModel)

Tailor the Result TableAfter all of the connections are established, the properties of theVapDefaultRelationshipTableModel have to be set. The bean needs to knowwhich columns of data you want to display in the result table. Double click onthe object to access its properties, then alter the columnIdentifiers row (clickon the little push button that appears in the row). Figure 115 shows thedialog used to set the object class and the properties (columns of the table)that we want to show in the output.

Figure 115. Column Identifiers

You must enter the full name of the class (itso.wasdb.persist.Employee) andthen its properties are displayed automatically in the middle pane. Select thedesired properties and click on Add to set the columns of the result table.

Chapter 9. Persistence Builder: VisualAge for Java 125

Page 150: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Test the ServletOnce you have completed all of these steps, your servlet should be ready torun. Press Ctrl-S to save your work and then click on the Run icon on the toolbar. This starts the WebSphere Test Environment (servlet runner) anddisplays the HTML page with the default browser (Figure 116).

Figure 116. Servlet Test Output

The servlet does not activate the datastore you have created with thePersistence Builder tool. For the servlet to work, you must activate thedatastore before doing any processing. The best place to add the datastoreactivation is the initialize method of the servlet:

itso.wasdb.persist.Services.ITSOItsoDataStore.singleton().activate();

The singleton method creates one instance of the datastore (independent ofhow many times it is called), and the activate method starts the datastore.Place the statement after the comment line // user code begin (1). Thiscode is preserved even if the method is regenerated.

Notice

126 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 151: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Changing the Datastore DatabaseOnce you have created the persistent servlet, it is possible to change whichdatabase manager product is used for persistent storage. You must duplicatethe complete database in the new database manager product. The details ofcompleting this task is beyond the scope of this book.

To change the datastore, simply regenerate the services class of thepersistent servlet from the Model Browser. This time specify the connectioninformation for the new database manager product.

Another way to change which database product is used as a datastore is tomake a small manual change in the datastore services class. The databaseconnection information is stored in the getConnectionSpec method of theITSOItsoDataStore class in the itso.wasdb.persist.Services package.

This code controls the driver and connection information that your objectuses to communicate with the database. By changing the driver andconnection information, we can change the database product, as long asidentical tables exist in the different database managers. Figure 117 showsthe correct settings for our example to interact with DB2, Oracle, and SQLServer. Note that this code is removed if you regenerate the service classes!

Figure 117. Establishing Connections to Multiple Database Vendors

//* WARNING: THIS METHOD WILL BE REGENERATED. */public com.ibm.ivj.db.base.DatabaseConnectionSpec getConnectionSpec() {

DatabaseConnectionSpec aConnectionSpec;

DatabaseConnectionSpec forDB2, forOracle, forSQLServer;// DB2 UDB app driverforDB2 = new DatabaseConnectionSpec

("VA1","COM.ibm.db2.jdbc.app.DB2Driver", "jdbc:db2:itsowdb");// Oracle thin driverforOracle = new DatabaseConnectionSpec

("VA1","oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@localhost:1521:orcl");

// SQL Server jdbc/odbc bridgeforSQLServer = new DatabaseConnectionSpec

("VA1","sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:SQLServer");

aConnectionSpec = forDB2;// aConnectionSpec = forOracle;// aConnectionSpec = forSQLServer;

aConnectionSpec.setLogonSpec(new DatabaseLogonSpec ("itso", "itso"));return aConnectionSpec;

}

Chapter 9. Persistence Builder: VisualAge for Java 127

Page 152: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Deploying a Servlet to WebSphereYour new servlet is ready to run on the WebSphere server, but you mustmake sure that all the proper resources are available on the Web server. Fordetailed instructions on deploying persistent servlets to WebSphere, seechapter 20 of the IBM redbook VisualAge for Java Enterprise Version 2:Persistence Builder with GUIs, Servlets, and Java Servlet Pages, SG24-5426.

The first thing to move to WebSphere is the datastore. Be sure that thedatabase tables and files are available on the WebSphere server. It isimportant that the database is identical to the database used in the testenvironment.

Next export all of the servlet code and copy it to WebSphere. In our example,we created three packages which must be exported (Figure 118). Place all ofthese classes in the WebSphere servlet directory.

Figure 118. Exporting the Servlet

128 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 153: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

With the code moved to WebSphere, it is imperative that all of the classesthat your persistent application utilizes are available in the WebSphereenvironment.

We do not go through all of the WebSphere administration pages. For now,the most important setting to get VisualAge for Java servlets to work is theclass path setting, and that is on the Setup -> Java Engine page (Figure 119).

Figure 119. WebSphere Application Server: Java Engine Setup

We used the following class path:

D:\jdk1.1.6\lib\classes.zip; <=== JDKD:\WebSphere\AppServer\classes; <=== export directoryD:\WebSphere\AppServer\web\classes;D:\SQLLIB\java\db2java.zip; <=== DB2 JDBC DriversD:\orant\Jdbc\lib\classes111.zip; <=== Oracle JDBC DriversD:\IBMVJava\eab\runtime20\ivjdab.jar; <=== data access beansD:\IBMVJava\eab\runtime20\ivjsb21.jar; <=== servlet builderD:\IBMVJava\eab\runtime20\ivjpb20.jar; <=== persistence builderD:\IBMVJava\eab\runtime20\ivjpb20e.jar; <=== pers. builder extras

(see below)D:\IBMVJava\hpj\lib\swingall.jar; <=== swing

Chapter 9. Persistence Builder: VisualAge for Java 129

Page 154: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

To simplify the class path, we copied the JAR files into the directoryD:\WebSphere\AppServer\lib. Jar files in the lib subdirectory are automaticallyadded to the WebSphere class path and do not have to be specified in theadministration setup.

Three of these JAR files are special cases:

❑ The ivjpb20e.jar file is not provided by VisualAge for Java. We built thisfile ourselves by exporting the VisualAge Persistence Extras project fromVisualAge for Java. This is the project with the additional classes tointeract with AWT and Swing from Persistence Builder home andrelationship collections.

❑ The ivjdab.jar file contains the same classes as the databean.jar fileprovided by WebSphere, plus extra GUI classes. To make sure that theivjdab.jar file is loaded before the databean.jar file, we added it to theclass path.

❑ The ivjpb20.jar file contains the same classes as the ejs.jar file providedby WebSphere, plus extra classes. To make sure that the ivjpb20.jar file isloaded before the ejs.jar file, we added it to the class path.

Your persistent servlet should successfully run in WebSphere with this classpath setting.

130 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 155: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

10 EnterpriseJavaBeansIn this chapter we will briefly discuss what Enterprise JavaBeans are andhow they are used in conjunction with WebSphere, VisualAge for Java, anddatabases.

For further information refer to http://java.sun.com/products/ejb/docs.html orto the redbook Enterprise JavaBean Development with VisualAge for Java,SG24-5429.

Note that Enterprise JavaBeans is the name of the architecture as specifiedby Sun; what we develop we will simply call enterprise beans.

© Copyright IBM Corp. 1999 131

Page 156: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Enterprise JavaBeans from a Bird’s-Eye PerspectiveAn Enterprise JavaBean is a nonvisual component which runs on the serverside of a distributed application. The enterprise bean itself lives in anenvironment called an EJB container. The EJB container in turn runs in anEJB server or Enterprise Java Server (EJS). The goals of the EJBarchitecture include:

❑ Making life easier for the developer: The developer does not have tostruggle with low-level entities such as persistence, threads, andtransactions; in that the EJB architecture enables the developer toconcentrate on the business logic.

❑ Making server applications portable: The model ensures that Javaplatform server components can be developed once and deployedanywhere.

❑ Making the server application independent: The Enterprise JavaBeansarchitecture is completely independent from any specific platform,protocol, or middleware infrastructure. Applications that are developedfor one platform can be picked up, moved, and redeployed to anotherplatform.

A Closer LookSo far we have seen the abstract term of enterprise bean, EJB containers,and EJB servers. We will now take a closer look at those terms.

There are two types of enterprise beans: session beans and entity beans.

❑ Session beans can be stateful or stateless. Stateful session beans existfor the duration of a single client/server session. Stateless session beansare pooled by the container to handle multiple requests from multipleclients.

❑ Entity beans contain persistent data that can be saved in variouspersistent data stores. Each entity bean carries its own identity; thatmeans entity beans do have primary keys. Entity beans that manage theirown persistence are called bean managed persistence (BMP) entity beans.Entity beans that delegate their persistence to the EJB container arecalled container managed persistence (CMP) entity beans.

The home interface specifies the available methods for locating, creating,and removing instances of enterprise bean classes. This is normally providedby the developer.

132 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 157: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The remote interface specifies the business methods of the enterprise bean.Typically, the developer of the enterprise bean also defines the remoteinterface.

An EJB container is a runtime environment that manages one or moreenterprise beans. Specifically, containers manage the life cycles of enterprisebean objects, coordinate distributed transactions, and implement objectsecurity. The deployment descriptor, a serialized object that containsrun-time settings for an enterprise bean, tells the EJB container how tomanage and control an enterprise bean. Generally, each EJB containercontains a set of enterprise beans. EJB containers are typically provided byEJB servers.

An EJB server is a high-level process or application that provides arun-time environment to support the execution of server applications thatuse enterprise beans. An EJB server provides a JNDI-accessible namingservice, manages and coordinates the allocation of resources to clientapplications, provides access to system resources, and provides a transactionservice. An EJB server could be, for example, a database or applicationserver.

Developing a Container Managed Persistence EntityBean

In this section we develop a simple enterprise bean. Because this book isabout WebSphere and database integration, we develop this entity beanbased on the employee/department sample that we are using throughout thisbook. For the development process we utilize VisualAge for Java. Moreoverwe show how to deploy the enterprise bean to use it within WebSphere from aservlet, and we also show how to use this enterprise bean from an applet orapplication.

In our version of WebSphere Application Server (Version 2.0.2), and also inthe WebSphere Test Environment of VisualAge for Java, containermanaged persistence (CMP) only works with DB2 and not with Oracle andSQL Server. Therefore, this first example will only work with DB2.

The next example uses bean managed persistence (BMP) and works withall JDBC compliant databases.

Notice

Chapter 10. Enterprise JavaBeans 133

Page 158: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Setup of VisualAge for JavaFollow these steps to set up VisualAge for Java:

❑ Make sure you added the IBM EJB Development Environment 1.1 featureto VisualAge for Java. To see whether you have installed this feature, goto File -> Quick Start, select Features on the left side and Delete Featureon the right side. This will show you all installed features (Figure 120).

Figure 120. Available Features

❑ Add the feature if it has not been added to the Workbench.

❑ In your project (we used ITSO SG24 5471 as the project name) create anew package called itso.wasdb.ejb. This will contain the enterprise beanwe develop.

❑ Next go to the EJB pane in the Workbench (Figure 121).

❑ Now create a new EJB group in the EJB pane. From the EJBs menuselect Add -> EJB Group. Select the project (ITSO SG24 5471) and givethe EJB group the name ITSO_EJBs.

134 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 159: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 121. EJB Development Pane: Adding an EJB Group

Create a Department Enterprise BeanTo create an enterprise bean:

❑ From the context menu of the new EJB group select Add -> EJB. Our firstEJB will be related to the department table already used throughout thebook, so name the bean Department. As we want the container to managethe persistence service, select Entity Bean with container managedpersistence fields (CMP) as the bean type. Select the project (ITSO SG245471) and the itso.wasdb.ejb package (Figure 122).

Chapter 10. Enterprise JavaBeans 135

Page 160: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 122. EJB SmartGuide

In the next dialog of the SmartGuide you do not have to make anychanges, so click on Finish.

❑ The SmartGuide has now created a very basic framework for the EJB. Itshould have created three interfaces and two classes:

• Department interface: This currently offers no methods to beimplemented. Later on, this will contain the abstract methoddeclarations of all methods that will be implemented by theDepartmentBean class, which represents the business logic.

• DepartmentBean class: This class will contain the actual businesslogic. The SmartGuide has already created several methods for thisclass, including a method that creates the EJB. Because this is anentity bean, the SmartGuide also created a primaryKey property.

136 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 161: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

• DepartmentBeanFinderHelper interface: This should be empty at thecurrent state. It might later contain specialized SQL search stringsthat allow a certain order within the various EJB instances.

• DepartmentHome interface: This contains a method to find a specificbean by its primary key or create a new bean with a new primary key.

• DepartmentKey class: This class represents the primary key for theentity bean. For the Department table, this will be mapped to theDEPTNO column.

Add the Properties and Methods to the BeanNow we add the actual properties and business logic to the skeleton classes.

❑ The properties are basically nothing but the columns from the departmenttable. The business logic in this example is limited to get and set methodsfor the properties. The department table consists of the following columns:DEPTNO, DEPTNAME, MGRNO, ADMRDEPT, and LOCATION.Therefore, the DepartmentBean contains the matching properties and alsothe get and set methods for the properties, except for the primary keyproperty that should not be alterable.

As described in the previous step, the SmartGuide already created aprimary key property. Because it should match the department table, thefirst action is to add the deptNo property and make it the primary keyfield. Highlight the DepartmentBean class in the Types pane and use theCreate Field SmartGuide to add a public field named deptNo of typeString. Let the SmartGuide to create a get method for this property, but aset property is not appropriate for a primary key (Figure 123).

Figure 123. Adding a Field

Chapter 10. Enterprise JavaBeans 137

Page 162: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Now make the deptNo field the primary key field. Click on the fields iconin the Type pane (Figure 124). The Types pane is now changed to a Fieldspane.

Here you see all the fields (properties) of the bean. It contains now threeproperties, the primaryKey property, an entityContext property, and thenewly created deptNo property. The primaryKey property is currently thekey field (it has the key icon on the right side) and it is a containermanaged field, identified by the cup-like icon on the right side.

Figure 124. Switching to the Fields Pane

To make the deptNo property the primary key, right-click on that deptNoentry and select Key Field. It should now show both icons, the cup and thekey.

138 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 163: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Now we delete the primaryKey property generated by the SmartGuide byremoving it from the bottom source pane. After deleting the primaryKeyproperty, the ejbCreate method in the Methods pane reports a problemthat we have to repair. In the method body of ejbCreate, replaceprimaryKey by deptNo (deptNo = key.deptNo;).

❑ Everything is now ready to add the rest of the properties. Switch back tothe Types pane and select the DepartmentBean class. Use the Create FieldSmartGuide to add the deptName, location, mgrNo, and admrDeptproperties (all public, of type String, with getter and setter methods).

❑ By now your Methods pane should be a bit more filled. Next, make all thegetter and setter methods available to the EJB Remote Interface. To dothis, right click each getXXX and setXXX method, and select Add To ->EJB Remote Interface (Figure 125). After this, each method contains alittle unidentifiable icon on the right, and the department interface offersall the methods you have just added to the remote interface.

Figure 125. Add Methods to the Remote Interface

Chapter 10. Enterprise JavaBeans 139

Page 164: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Next, mark all the properties we have defined to be persistent. Switchback to the Fields pane, right click on each field and mark it ContainerManaged (Figure 126).

Figure 126. Marking Properties Container Managed

Map the Bean to the SchemaThe bean is persistent in the relational database. We import the databaseschema and map the properties of the bean to the columns of the departmenttable. We describe this only briefly because we covered schema mapping indetail in Chapter 9, “Persistence Builder: VisualAge for Java” on page 109.

❑ Start the Persistence Builder Schema Browser from the menu EJBs ->Open To -> Database Schemas.

❑ From the menu select Schemas -> Import / Export Schema -> ImportSchema from Database and name the new schema ITSO_Schema.

❑ Specify driver, URL, user ID, and password (Figure 127).

Figure 127. Connection Information for the Schema Import

140 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 165: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Build the table list based on the ITSO qualifier and select theDEPARTMENT table (Figure 128).

Figure 128. Select the Table to Import

❑ We do not have to modify the imported schema (Figure 129). Close theSchema Browser.

Figure 129. Schema Browser after Import

Chapter 10. Enterprise JavaBeans 141

Page 166: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ After importing the schema we perform the mapping. Open the MapBrowser by selecting EJBs -> Open To -> Map Schema. From theDatastore_Maps menu select New EJB Group Map. Name the mapITSO_Map, select the EJB group and the schema (Figure 130).

Figure 130. Specifying the Datastore Map for the Enterprise Bean

❑ The next step is to associate the properties of the EJB to the columns ofthe department table. Select Table_Maps -> New Table Map -> Add TableMap with No Inheritance and select the DEPARTMENT table (Figure131).

Figure 131. Map Browser

142 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 167: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ We associate each property to an attribute of the database table. Open theProperty Map Editor from the context menu of the DEPARTMENT tablemap. Click on the Map Type in each column to select the Simple mappingand go on to select the matching column from the database table (Figure132). When done, close the property map editor and the Map Browser.

Figure 132. The Property Map Editor

Generate the Code and TestNow everything is prepared to generate the code:

❑ Right-click on the EJB group ITSO_EJBs and select Generate -> DeployedCode.

❑ Right-click on the EJB group ITSO_EJBs and select Generate -> TestClient.

As a result the Types pane now shows more classes.

To test an enterprise bean VisualAge for Java contains a basic EJB server. Toadd the enterprise bean to the EJB server, right-click on the ITSO_EJBs EJBgroup and select Add To -> Server Configuration (Figure 133).

Chapter 10. Enterprise JavaBeans 143

Page 168: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 133. EJB Server Configuration Dialog

Starting the EJB Server in the Test EnvironmentNow we have to start each of the services:

❑ Start the Location Service Daemon. Right-click on it and select StartServer.

❑ Next start the Persistent Name Server the same way.

❑ Before you start the EJB server itself, ensure that the properties arecorrect. Right-click on the EJB Server and select Properties. Make surethe database URL (jdbc:db2:itsowdb), user ID (ITSO) and password (itso)are correct (Figure 134).

Figure 134. EJB Server Properties

144 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 169: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Finally start the EJB server. The console should display all the servers asshown in Figure 135. The server is now ready and the enterprise bean isdeployed in the test environment.

Figure 135. EJS Console Output

Wait for all the servers to be ready before continuing with testing.

Using the Test ClientNow we can test the enterprise bean with the test client we generated a fewsteps earlier.

❑ Select the Department EJB in the EJB Server Configuration Window andclick on the Run Test Client button (the yellow running man icon in Figure133) to open the test client window.

The test client window is the same for all enterprise beans (Figure 136).

Chapter 10. Enterprise JavaBeans 145

Page 170: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 136. Test Client

❑ Click the Connect Button and the test client presents the home interfaceof our department bean (Figure 137). This is only used to find or create aninstance of the department enterprise bean.

Figure 137. The Home Interface

146 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 171: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ Now we retrieve a department with a given primary key:

• Select the findByPrimaryKey entry in the list of methods on the leftside.

• Click on the New button in the parameters list on the right side.

• Select new DepartmentKey(String) in the constructors pane and entera department number (for example, E21) as the parameter in theDepartmentKey dialog (Figure 138).

• Click on the Send button and then on the Done button.

Figure 138. Parameter Specification for the DepartmentKey

❑ Back in the Home Interface Dialog (Figure 137) click the Send button andthe Home Interface should change to the Remote Interface, whichrepresents the remote interface for the actual business logic.

• You may now execute the methods of the enterprise bean; for example,to retrieve the department name, select the getDeptName method andclick the Send button (Figure 139).

• You can use the setXxxxx methods to change the values in thedepartment bean retrieved. Each Send of a set method changes thecolumn value in the table. (You can open a DB2 command window toverify the changes in the table.)

Chapter 10. Enterprise JavaBeans 147

Page 172: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 139. Test Client Presenting the Remote Interface

❑ You may now play around with the test client. For instance, you mightcreate a new DepartmentBean using the home interface, and use thesetXxxx methods to set the properties and therefore the column values inthe department table.

Note that the Send key for the create(DepartmentKey) method returnswith an error message from DB2:

com.ibm.ejs.container.ContainerException: com.ibm.ejs.persistence.EJSPersistenceException: COM.ibm.db2.jdbc.app.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0407N Assignment of a NULL value to a NOT NULL column "" is not allowed. SQLSTATE=23502

The columns DEPTNAME and ADMRDEPT were defined as not null. Wehave to provide initial values. We can change the create(DepartmentKey)method in the EJB Workbench pane to set default values for the requiredfields:

public void ejbCreate(DepartmentKey key) {// All CMP fields should be intialized here.deptNo = key.deptNo;deptName = "Unknown";admrDept = " ";

}

With this change the creation of a new department works. Thedepartment name and the other fields (columns) can be changedafterwards using the set methods.

148 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 173: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Deploy the Enterprise Bean to WebSphereThe next step is to extract the enterprise bean and take it into a realenvironment, which is the WebSphere Application Server. WebSphereprovides an infrastructure to run a container-managed persistence entitybean coded according the Sun’s EJB specification.

To deploy a bean within the WebSphere Application Server, perform thefollowing steps:

❑ First, export a JAR file containing the bean. You have two choices here:

• One way is to export an already deployed version of the bean.VisualAge for Java can do this for you. The advantage of this method isthat WebSphere keeps the mapping from the bean properties to thetable attributes.

To export the JAR file, right-click on the department EJB in the EJBspane and select Export -> EJS Jar. You should place the resulting JARfile in the deployableEJBs directory of WebSphere (for example,c:\WebSphere\AppServer\deployableEJBs\DepartmentEJS.jar).

• The other way is to export just the bean code and let WebSphere do thedeployment process. But this has the effect that the mapping which wehave just done will be lost. During the deployment process, WebSpherewill try to create a new schema and a new table in the schema, whichreflects the properties of the bean. If we had started from scratch, thismethod might be fine, but because we already have some data in ourdatabase, this is not appropriate.

Export the JAR file (Export -> Export EJB Jar) and WebSphere will dothe main part of the deployment process.

❑ The next step is to generate a new EJB container in WebSphere. Thiscontainer holds the database specification: URL, user ID, and password. IfWebSphere supports other database systems for container-managedbeans this might be the place where you must also specify the driver. Butbecause WebSphere currently only supports DB2, we do not have toprovide a driver.

To create a new container, open the WebSphere administration applet. Goto the Enterprise Java Services -> Global Settings. Make sure EJS isenabled and the host name matches your machine name (Figure 140). Ifyou use localhost, later on you will not be able to access the EJB remotely.Apparently the naming service on the machine running the EJB serverdifferentiates between localhost and servername.

Chapter 10. Enterprise JavaBeans 149

Page 174: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 140. WebSphere General EJB Settings

❑ In the Containers section add a new container with the nameITSOContainer. Select the container and provide the specification:

• Because we have written an entity bean, we will use thecom.ibm.ejs.container.EJSEntityContainer class. This is one of twocontainer classes which WebSphere provides. The other containerclass, which is for session beans, is accordingly namedcom.ibm.ejs.container.EJSSessionContainer.

• Next we have to specify the JDBC URL: jdbc:db2:itsowdb.

• The directory in which to put the deployed beans is deployedEJBs.

• Finally, specify the user ID and password (ITSO and itso).

At the bottom of this pane, you will notice a list box that shows the beansthat are already deployed in the selected container. Because we have justcreated a new container, no beans are listed here.

Click on Save to preserve the changes (Figure 141).

150 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 175: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 141. WebSphere Container EJB Settings

❑ Now we are ready to deploy the bean. In the EJB Jar Files pane (Figure142), select the DepartmentEJS.jar on the left and click the Deploy button.

Figure 142. EJB Jar File Pane

❑ In the Deploy Jar File dialog, select the ITSOContainer from thecombobox and click on Deploy (this dialog is not shown).

Chapter 10. Enterprise JavaBeans 151

Page 176: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ WebSphere should now present a dialog box, warning you that thedeployment was already done (Figure 143). Do not regenerate the jar file,only redeploy it (click on Redeploy Existing). If you regenerate, WebSpherewill loose the mapping from the bean properties to the database table andwill create a new schema and table, which is not what we want to happen.

Figure 143. Redeployment Warning

❑ You should receive a message that the Department bean was deployedsuccessfully.

❑ To make the bean available, it is necessary to restart WebSphere. Stop theWebSphere Servlet Service and the IBM HTTP Server and restart theHTTP Server (which in turn should start up WebSphere as well).

❑ You can test the deployed bean by using the test client from VisualAge forJava. After starting the test client, connect to the bean using the URL:

iiop://hostname:9019

WebSphere will not start the EJB services properly if there are any entitycontainers that are invalid in terms of using a non-existent ornon-accessible database. For example, if you did not reate the sampledatabase from DB2, then the defaultEntityContainer will not be able tostart because the database it uses is not there. In case of such a failure,WebSphere apparently does not start up the services at all.

The simplest and safest solution is to remove all unusedcontainers. Do this by inspecting all containers in respect to thedeployed beans they contain.

Notice

152 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 177: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Access the Department Bean from a ServletNow that our bean is deployed, how can we access it? In our first example, weaccess the enterprise bean through a servlet. This servlet is very simple andcontains nothing exciting except for the methods to create or find ourenterprise bean. The servlet enables the user to retrieve a bean and to showand update its properties.

The servlet (DepartmentEJBServlet class in itso.wasdb.ejb.servlet package)contains the following methods:

❑ doPost and doGet: Both methods just call the performTask method. Thismakes the servlet independent of the selected HTTP method to transferthe form data. We will not list these methods here, instead refer to Figure85 on page 101.

❑ performTask: Based on the request, this method directs the flow either tothe getDepartment method or the updateDepartment method.

❑ getParameter: This is a simple helper method to retrieve a parameter froman HTTP request object. See Figure 84 on page 100.

❑ init: This initializes the servlet. This method contains the code to start aconnection to the EJB server.

❑ createOrtFindDepartment: Based on a given key, this method tries to finda department; and if that department does not exist, it creates a new one.

❑ getDepartment: This method retrieves a department bean and present itscontents in an HTML form that enables the user to update the bean. Italso attaches the bean to the session for usage in the next interaction.

❑ updateDepartment: This method performs the update of the contents ofthe bean. Based on the form data, it uses the setter methods of the beanthat was retrieved in the getDepartment method.

Class DeclarationThe DepartmentEJBServlet’s class declaration is shown in Figure 144. Itcontains two class variables:

❑ The departmentHome Variable represents the home interface of theDepartmentBean

❑ The initContext represents the initial context of the naming service. Thismakes it possible to retrieve the home interface of the department bean.

Chapter 10. Enterprise JavaBeans 153

Page 178: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 144. DepartmentEJBServlet Class Declaration

Perform Task MethodThe performTask method is simple. Depending on the request, it calls eitherthe getDepartment or the updateDepartment method (Figure 145).

Figure 145. DepartmentEJBServlet performTask Method

InitializationThe init method (Figure 146) initializes the servlet. It retrieves the initialcontext, which provides a starting point for naming and directory operations.Once we have this initial context, we can use it to look up other contexts andobjects. This is done in the next few lines of code.

The initial context is used to look up an object that is registered under thename Department. Using a static helper method from the generated code,this object is then cast to an object of type DepartmentHome, which is thehome interface of the department bean and serves for creating and finding ofa department enterprise bean. The resulting object is stored in thedepartmentHome class variable .

package itso.wasdb.ejb.servlet;

import javax.servlet.http.*;import javax.servlet.*;import itso.wasdb.ejb.*;

public class DepartmentEJBServlet extends HttpServlet {

DepartmentHome departmentHome = null;InitialContext initContext = null;

public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

String command = getParameter(request, "command");

if ( command == null || command.equals("getDepartment") )getDepartment(request, response);

else if (command.equals("updateDepartment"))updateDepartment(request, response);

// else print some error message ...

}

154 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 179: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 146. DepartmentEJBServlet init Method

Retrieve a Department BeanThe next method to look at is the getDepartment method that uses the homeinterface to either create a new enterprise bean or find an already existingbean based on the primary key given in the HTTP request (Figure 147).

We do not describe the method in detail, but will concentrate on theinteresting parts that are marked in bold face.

public void init(ServletConfig config) throws ServletException {

super.init(config);

System.out.println("Retrieving initial context...");java.util.Hashtable properties = new java.util.Hashtable(2);// local name server// comment next line to run within VA Javaproperties.put(javax.naming.Context.PROVIDER_URL, "iiop://sonoma:9019");// IBM name servicesproperties.put(Context.INITIAL_CONTEXT_FACTORY,

"com.ibm.jndi.CosNaming.CNInitialContextFactory");

try {initContext = new InitialContext(properties);

Object obj;

// lookup the home interface using the JNDI nameSystem.out.println("Retrieving the home interface...");Object o = initContext.lookup("Department"); // this is the JNDI nameif (o instanceof org.omg.CORBA.Object)

departmentHome = DepartmentHomeHelper.narrow((org.omg.CORBA.Object) o);System.out.println("Creating DepartmentHome...");

} catch (NamingException e) {throw new ServletException(e.toString());

}

}

Chapter 10. Enterprise JavaBeans 155

Page 180: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 147. DepartmentEJbServlet getDepartment Method

public void getDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);

// Get the output writerjava.io.PrintWriter out = response.getWriter();

// Get the deptNo to look forString deptNo = getParameter(request, "deptNo");

out.println("<HTML><HEAD><TITLE>DepartmentEJBServlet </TITLE></HEAD><BODY>");

try {Department dep = createOrFindDepartment(deptNo);

out.println("<TABLE> <FORM ACTION" +"= \"/servlet/itso.wasdb.ejb.servlet.DepartmentEJBServlet\">");

out.println("<TR>");out.println("<TH>Department Number");out.println("<TH>Department Name");out.println("<TH>Department Location");out.println("<TH>Admr. Department");out.println("<TH>Manager Number");

out.println("<TR><TD>" + deptNo);out.println(" <TD><INPUT TYPE=TEXT NAME=deptName VALUE=\"" +

dep.getDeptName() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=location VALUE=\"" +

dep.getLocation() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=admrDept VALUE=\"" +

dep.getAdmrDept() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=mgrNo VALUE=\"" +

dep.getMgrNo() + "\">");

out.println("<TR><TD><INPUT TYPE=HIDDEN NAME=command VALUE=updateDepartment>");out.println("<TD><INPUT VALUE=Update TYPE=SUBMIT>");out.println("</FORM></TABLE>");

HttpSession session = request.getSession(true);session.putValue("itso.wasdb.ejb.servlet.DepartmentEJBServlet.department",

dep);} catch (Exception e) {

out.println("<h2>Error: " + e + "</h2>");e.printStackTrace(out);

}out.println("</BODY></HTML>");

}

156 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 181: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The first point of interest is where the actual enterprise bean is obtained.This is done by the createOrFindDepartment method based on a primary keygiven in the HTTP request. The contents of this bean are then presented inan HTML form.

This leads to the next interesting point: The bean itself is attached to thecurrent HTTP session for later usage in the updateDepartment method.

Create or Find a Department BeanNow let us inspect the createOrFindDepartment method (Figure 148). Thismethod tries to find an enterprise bean, and if it cannot find one, it creates anew enterprise bean. Both operations utilize the home interface of thedepartment bean. In any case, it will return the bean to the caller.

Figure 148. DepartmentEJBServlet createOrFindDepartment Method

Update the Department BeanThe last method that is important for our servlet is the updateDepartmentmethod (Figure 149). The interesting parts are again shown in bold face.

Basically, the session that was created in the getDepartment method is usedto retrieve the attached department bean. Then, based on the form data, itfollows a simple sequence of setXxxx invocations of the department bean.That is the update!

public Department createOrFindDepartment(String key) throws NamingException, ObjectNotFoundException, RemoteException, CreateException {

Department dep = null;try {

dep = departmentHome.findByPrimaryKey(new DepartmentKey(key));} catch (javax.ejb.FinderException e) {

System.out.println("Department not found! Create new one");dep = departmentHome.create(new DepartmentKey(key));

}

return dep;}

Chapter 10. Enterprise JavaBeans 157

Page 182: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 149. DepartmentEJBServlet updateDepartment Method

Test the Servlet in VisualAge for JavaStart the WebSphere Test Environment (SERunner class) and make surethat the EJB server is running (see “Generate the Code and Test” onpage 143).

Comment one line in the init method (Figure 146 on page 155):

// properties.put(javax.naming.Context.PROVIDER_URL, "iiop://sonoma:9019");

Invoke the servlet with the URL:

http://127.0.0.1:8080/servlet/itso.wasdb.ejb.servlet.DepartmentEJBServlet?deptNo=E21

Executing the servlet results in the browser output shown in Figure 150.

public void updateDepartment(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);

java.io.PrintWriter out = response.getWriter();out.println("<HTML><HEAD><TITLE>Result</TITLE></HEAD><BODY>");

HttpSession session = request.getSession(false);Department dep = (Department)

session.getValue("itso.wasdb.ejb.servlet.DepartmentEJBServlet.department");

String location = getParameter(request, "location");String admrDept = getParameter(request, "admrDept");String mgrNo = getParameter(request, "mgrNo");String deptName = getParameter(request, "deptName");

dep.setLocation(location);dep.setAdmrDept(admrDept);dep.setMgrNo(mgrNo);dep.setDeptName(deptName);

out.println("<H1>Update ok</H1>");out.println("</BODY></HTML>");

}

158 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 183: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Test the Servlet in WebSphereNow let us try to invoke the servlet with the deployed enterprise bean underWebSphere. Export the class file of the servlet from VisualAge for Java to theWebSphere servlets directory:

c:\WebSphere\AppServer\servlets\itso\wasdb\ejb\servlet

Invoke the servlet with the URL:

http://hostname/servlet/itso.wasdb.ejb.servlet.DepartmentEJBServlet?command=getDepartment&deptNo=E21

Executing the servlet results in the browser output shown in Figure 150.

Figure 150. DepartmentEJBServlet in a Browser

You may now change the contents of the bean and click on Update. Keep inmind that you should not exceed the lengths of the fields; otherwise, theupdate will not succeed. For example, the Admr. Department may not belonger than three characters.

If the update was successful, the servlet will let you know. Click on Back toretrieve the enterprise bean again and verify that the bean has changed.

Chapter 10. Enterprise JavaBeans 159

Page 184: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Access the Department Bean from an ApplicationIn the same way that we have used a servlet to access our enterprise bean,we might want to use an application or an applet. We will develop a simplepanel that works the same way our servlet does. The user can enter adepartment number; if the department exists the applet will show itscontent, if not it will create a new department bean. This panel might beadded to an application or to an applet.

Create the GUI LayoutWe use VisualAge for Java to develop the applet.

❑ Create a new package called itso.wasdb.ejb.client.

❑ In this package create a new class called DepartmentPanel. Derive thisclass from the Swing JPanel class and mark the Compose the classvisually checkbox in the SmartGuide.

❑ In the Visual Composition Editor, design the panel.

The final panel with connections is shown in Figure 151.

Figure 151. Department Panel with All Connections

12

2 3

45

6

6

6

160 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 185: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Create the Connections1. First, we have to create a connection to the server to retrieve the initial

context and the home interface of the department bean. This requires amethod to initialize the context and the home interface based on theserver name. We will use a new method called createOrFind.

For the Create / Find Department button, select Event to Code from thecontext menu and enter the createOrFind method code (Figure 152).Notice that the code is almost the same as for the servlet (Figure 148 onpage 157), and again the error handling is only very rudimentary.

2. For the parameters of the method, select the text field next to theServername label and the text field next to the Create / Find Departmentbutton.

3. The createForFind method provides our department bean as a result. Tobe more precise, it provides an implementation of the Departmentinterface. To store this object we use a variable named department and weuse the context menu to change its type to Department. Therefore, weconnect the normalResult of the createOrFind method to our departmentvariable (this property).

4. Now that department is a valid object, we connect each property ofdepartment (admrDept, location, mgrNo, and deptName) to the matchingtext properties of the text fields.

5. For the Update button we connect actionPerformed to the setLocationmethod of department. Because the setLocation method requires aparameter, we provide it with the text property of the department nametext field.

6. Next, we do the same for the other properties: admrDept, mgrNo, anddeptName.

Chapter 10. Enterprise JavaBeans 161

Page 186: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 152. DepartmentPanel createOrFind Method

public itso.wasdb.ejb.Department createOrFind(String key, String adress) {

// Get the initial contextif (initContext == null) {

try {System.out.println("Retrieving initial context...");java.util.Hashtable properties = new java.util.Hashtable(2);// local name server// comment the next line to run inside VA Javaproperties.put(javax.naming.Context.PROVIDER_URL, "iiop://" + adress +

":9019");// IBM name servicesproperties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,

"com.ibm.jndi.CosNaming.CNInitialContextFactory");initContext = new javax.naming.InitialContext(properties);

} catch (javax.naming.NamingException e) {System.out.println("Error retrieving the initial context: " + e);

} // endtry}

Object obj;if (departmentHome == null) {

// lookup the home interface using the JNDI nametry {

System.out.println("Retrieving the home interface...");Object o = initContext.lookup("Department"); // this is the JNDI nameif (o instanceof org.omg.CORBA.Object)

departmentHome = DepartmentHomeHelper.narrow((org.omg.CORBA.Object) o);else

System.out.println("Type mismatch");} catch (javax.naming.NamingException e) {

System.out.println("Error retrieving the home interface: " + e.getMessage());

} // endtry}System.out.println("Creating Department...");Department dep = null;try {

dep = departmentHome.findByPrimaryKey(new DepartmentKey(key));System.out.println("Department found!");

} catch (javax.ejb.ObjectNotFoundException e) {

System.out.println("Department not not, create a new one");try {

dep = departmentHome.create(new DepartmentKey(key));} catch (Exception excp) {

excp.printStackTrace(System.out);System.exit(1);

}} catch (Exception e) {

e.printStackTrace(System.out);System.exit(1);

}return dep;

}

162 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 187: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Test the Applet or ApplicationBecause VisualAge for Java automatically creates a main method for testingpurposes, we can already test the panel. The normal way is to imbed theDepartmentPanel in an applet or application. We do not show how thisprocess is done because it is just a trivial step. However, the samplerepository provides an applet and an application that use theDepartmentPanel.

To test the panel, execute it, enter your server name and a valid departmentnumber, and click Create / Find Department button (Figure 153).

Figure 153. Department Panel Displaying the Department Bean

We were not able to access the department bean from an applet runninginside a browser, although it was possible to run the applet inside a remoteapplet viewer.

Presumably, this has something to do with the security restrictions underwhich the applet has to run inside a browser.

Notice

Chapter 10. Enterprise JavaBeans 163

Page 188: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Developing a Bean Managed Persistence Entity BeanIn this section we will develop an entity bean that manages its persistenceitself. For this example, we will take the second table of our sample databaseand develop a bean that stores its state to the employee table of the database.

We will again start with the SmartGuide of VisualAge for Java to create thebean.

Create an Employee Enterprise Bean with the SmartGuideSimilar to the process of adding a container managed bean, we now have toadd another bean to our ITSO_EJBs group (select Add To -> EJB).

Create a new enterprise bean, but this time select Entity Bean with Bean-managed Persistence (BMP) for the bean type. Name it Employee and add itto the itso.wasdb.ejb package (Figure 154).

Figure 154. Adding a BMP Bean

164 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 189: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Add Properties and MethodsNow we add the properties to the bean. This is similar to the steps we havedone for the CMP bean, except that it is not possible to mark a property to becontainer-managed, and there is also no way to mark a property to be theprimary key field (Figure 155).

For each column of the employee table, create a matching property withgetters and setters (no setter for the employee number). Add all getters andsetter to the remote interface (Add To -> EJB Remote Interface).

Figure 155. Properties in the Workspace View

The properties are listed in Table 3.

Table 3. Properties of the Employee Bean

Type Name Type Name

String empNo String firstName

String midInit String lastName

String workDept String phoneNo

java.util.Date hireDate String job

String sex java.util.Date birthDate

double salary double bonus

double comm short edLevel

itso.wasdb.ejb.EmployeeStorage

storage (private,no getter/setter)

Chapter 10. Enterprise JavaBeans 165

Page 190: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Provide the Employee Bean with Persistence FunctionalityThe only thing, apart from additional business functionality, is to provide thebean with the functionality that it can persist itself to some database system.

To implement the persistence, we have to understand which methods of thebean are invoked by the EJB container and what the purpose of each methodis. VisualAge for Java by default creates the following methods:

❑ public void ejbLoad(): This method is invoked by the container tosynchronize the bean according to the state represented in the database.This means that the enterprise bean has to be able to refresh itself fromthe table.

❑ public void ejbStore(): This is the counterpart of the ejbLoad method.It synchronizes the database according to the state of the enterprise bean.The bean has to able to write its state into the database.

❑ public EmployeeKey ejbFindByPrimaryKey(EmployeeKey key): Thismethod retrieves an object with a given key from the database andreturns the key.

❑ public EmployeeKey ejbCreate(EmployeeKey key): This method isinvoked when the client requests a new enterprise bean using the homeinterface method create(...). This method is usually the place to validatethe argument given from the client and to insert a new row in thedatabase table that represents the contents of the enterprise bean.

❑ public void ejbRemove(): The container invokes this method to end thelife of this enterprise bean. This is the place to delete the record thatrepresents this bean from the database.

❑ public void ejbActivate(): This method is invoked when the containerpicks an instance from the pool and assigns it to a specific enterprise beanobject. According to the EJB specification, this is not the place to read thestate of the bean from a database; this should be done in the ejbLoadmethod. The ejbActivate method gives the bean the chance to use,initialize, or acquire additional resources. This method is invoked by thecontainer prior to the invocation of ejbLoad.

❑ public void ejbPassivate(): This is the counterpart of the ejbActivatemethod. It gives the enterprise bean the chance to release any resourcesthat were acquired during the ejbActivate method. This method is calleddirectly prior to the invocation of the ejbStore method.

There are some more methods, but at the moment those are of no interest.We have to implement the ejbLoad, ejbStore, ejbFindByPrimaryKey,ejbCreate, and ejbRemove methods. Because we do not use any additionalresources, we can skip the ejbActivate and ejbPassivate methods.

166 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 191: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

To make the bean persistent, we use the IBM data access beans. The usage iscapsulated in the EmployeeStorage class. This class is responsible to create anew row, to retrieve a row, to update a row, or to delete a row from theemployee table of our database. Therefore, among the attributes thatrepresent the actual employee object, the EmployeeBean holds a privateinstance of an EmployeeStorage class, named storage.

In the following code snippets, we only describe how to find and update anentity bean and the respective database record. The actions to remove orcreate a new entity bean are very similar.

Methods of the Entity BeanThe code for the ejbFindByPrimaryKey method (and for most methods of theentity bean) is very short and simple. The main work is done in theEmployeeStorage class.

In this method we create a new instance of the EmployeeStorage (if notalready there) and invoke the findEmployee method with the instance of theenterprise bean and the primary key (Figure 156).

Figure 156. EmployeeBean ejbFindByPrimaryKey Method

The ejbStore method to store the entity bean and synchronize its contentswith the database is also rather simple. The only thing done here is to invokethe update method of the storage class (Figure 157).

Figure 157. EmployeeBean ejbStore Method

public EmployeeKey ejbFindByPrimaryKey (EmployeeKey key) throws javax.ejb.FinderException {

try {if (storage == null)

storage = new itso.wasdb.ejb.EmployeeStorage();this.empNo = key.primaryKey;storage.findEmployee(this, key.primaryKey);

} catch(Exception e) {throw new FinderException(e.toString());

}return key;

}

public void ejbStore () throws java.rmi.RemoteException {try {

storage.updateEmployee(this);} catch (com.ibm.db.DataException e) {

throw new RemoteException(e.toString());}

}

Chapter 10. Enterprise JavaBeans 167

Page 192: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 158 shows some of the other methods.

Figure 158. EmployeeBean Methods

public void ejbActivate() throws java.rmi.RemoteException {try {

storage = new itso.wasdb.ejb.EmployeeStorage();} catch (Exception e) {

throw new RemoteException(e.toString());}

}public void ejbPassivate() throws java.rmi.RemoteException {

try {storage.close();

} catch (com.ibm.db.DataException e) {throw new java.rmi.RemoteException(e.toString());

}storage = null;

}public void ejbLoad() throws java.rmi.RemoteException {

if (storage == null)throw new RemoteException("Storage not initialized");

try {storage.findEmployee(this, empNo);

} catch (com.ibm.db.DataException e) {throw new RemoteException(e.toString());

}}public void ejbRemove() throws java.rmi.RemoteException {

try {storage.deleteEmployee(empNo);

} catch (com.ibm.db.DataException e) {throw new RemoteException(e.toString());

}}public EmployeeKey ejbCreate(EmployeeKey key, String firstName, String midInit,

String lastName, String workDept, String phoneNo, java.util.Date hireDate, String job, short edLevel, String sex, java.util.Date birthDate, double salary, double bonus, double comm) throws CreateException {

this.empNo = key.primaryKey;this.firstName = firstName; this.lastName = lastName; this.midInit = midInit; this.edLevel = edLevel; this.workDept = workDept; this.phoneNo = phoneNo;this.hireDate = hireDate; this.job = job; this.sex = sex; this.comm = comm;this.birthDate = birthDate; this.salary = salary; this.bonus = bonus;try {

if (storage == null) storage = new itso.wasdb.ejb.EmployeeStorage();storage.createEmployee(this);

} catch(Exception e) {throw new CreateException(e.toString());

}return key;

}

168 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 193: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The EmployeeStorage ClassNow we implement the EmployeeStorage class, and specifically, the twomethods of the storage class that were used in the two methods of the entitybean, namely the findEmployee method and the updateEmployee method.

Class DeclarationWe start with the declaration of the class (Figure 159).

Figure 159. EmployeeStorage Class Declaration

package itso.wasdb.ejb;

import java.sql.Connection;import java.sql.Types;import com.ibm.db.*;import java.util.Date;import java.util.Calendar;import java.math.BigDecimal;

public class EmployeeStorage {

static int database = 1; // DB2 final static String URL = "jdbc:db2:itsowdb";

final static String DRIVERNAME = "COM.ibm.db2.jdbc.app.DB2Driver";/*static int database = 2; // Oraclefinal static String URL = "jdbc:oracle:thin:@sonoma:1521:orcl";final static String DRIVERNAME = "oracle.jdbc.driver.OracleDriver";static int database = 3; // SQL Serverfinal static String URL = "jdbc:odbc:SqlServer";final static String DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";*/final static String USER = "ITSO";final static String PASSWORD = "itso";

static String SELECT ="SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, " + "JOB, SEX, SALARY, BONUS, COMM, HIREDATE, BIRTHDATE, EDLEVEL " +

"FROM ITSO.EMPLOYEE WHERE EMPLOYEE.EMPNO = :EMPNO";final static String INSERT ="INSERT INTO ITSO.EMPLOYEE VALUES (:EMPNO, :FIRSTNME, :MIDINIT, :LASTNAME,

:WORKDEPT, :PHONENO, :JOB, :SEX, :SALARY, :BONUS, :COMM, :HIREDATE, :BIRTHDATE, :EDLEVEL)";

final static String DELETE ="DELETE FROM ITSO.EMPLOYEE WHERE EMPNO = :EMPNO";

static StatementMetaData selectMetaData = null;static StatementMetaData insertMetaData = null;static StatementMetaData deleteMetaData = null;static DatabaseConnection dbConn = null;SelectResult resultSet = null;

}

Chapter 10. Enterprise JavaBeans 169

Page 194: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The EmployeeStorage class defines the database that will be used, the userID, and the password. It also contains static references to the different SQLstatements: select, insert and delete. The actual statements will be createdlater, we only define the string constants here. Notice that no update string isdefined. The update is done through the data access bean. We do not have todefine anything for this. At the very bottom we define a nonstaticSelectResult. This result will be used to update a row fetched from thedatabase.

This example uses the DB2 database, but we could have used any otherdatabase that provides the ITSOWDB database as well, although the codediffers a little bit (see “Different Mapping of SQL Types” on page 264).

Initializing the Meta DataThe next method we describe is the method that initializes the meta data forthe select statement. This method is static because the actual selectstatement is the same and independent of specific instances of the entitybean (Figure 160).

Figure 160. Initialize the Select Statement

static void initSelect() throws DataException {selectMetaData = new StatementMetaData();selectMetaData.setSQL(SELECT);// Use the default mapping, Oracle seems to have problems otherwiseselectMetaData.addParameter("EMPNO", String.class, Types.CHAR);// Next define all ouput parameter in the same wayselectMetaData.addColumn("EMPNO", String.class, Types.CHAR);selectMetaData.addColumn("FIRSTNME", String.class, Types.VARCHAR);selectMetaData.addColumn("MIDINIT", String.class, Types.CHAR);selectMetaData.addColumn("LASTNAME", String.class, Types.VARCHAR);selectMetaData.addColumn("WORKDEPT", String.class, Types.CHAR);selectMetaData.addColumn("PHONENO", String.class, Types.CHAR);selectMetaData.addColumn("JOB", String.class, Types.CHAR);selectMetaData.addColumn("SEX", String.class, Types.CHAR);

if (database == 1) { //DB2selectMetaData.addColumn("SALARY", Double.class, Types.DECIMAL);selectMetaData.addColumn("BONUS", Double.class, Types.DECIMAL);selectMetaData.addColumn("COMM", Double.class, Types.DECIMAL);selectMetaData.addColumn("HIREDATE", Types.DATE, Types.DATE);selectMetaData.addColumn("BIRTHDATE", Types.DATE, Types.DATE);selectMetaData.addColumn("EDLEVEL", Short.class, Types.SMALLINT);

}else if (database == 2) { //Oracle

selectMetaData.addColumn("SALARY", Types.DECIMAL, Types.DECIMAL);...

}// Define the table name which is used in the queryselectMetaData.addTable("ITSO.EMPLOYEE");

}

170 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 195: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The code of this method is specific for DB2, because Oracle and the SQLServer differ in they way they map SQL types (see “Different Mapping ofSQL Types” on page 264). Due to that, we had to use different specificationsfor the meta data for the different databases. The sample code of this classcontains the code for all three database systems.

ConstructorThe constructor calls the initialize method to set up a database connectionand the meta data for the select, insert, and delete statements (Figure 161).

Figure 161. EmployeeBean ejbStore Method

The initDelete and initInsert methods are similar to the initSelect method.

Find an EmployeeAs we saw in Figure 156 on page 167 the ejbFindByPrimaryKey method usedthe findEmployee method of the EmployeeStorage class. This method uses themeta data for the select statement, which was initialized in the initSelectmethod.

The findEmployee method is rather simple: A new SelectStatment is createdwhich uses the database connection and the prepared meta data to run aquery against the database. If a row was found, the employee bean is filledwith the column contents of that row (Figure 162).

Notice that the method does not close the resultSet, and that this resultSet isan instance variable of the class.

public EmployeeStorage() throws DataException {super();initialize();

}private void initialize() throws DataException{

// user code begin {1}if (dbConn == null) {

initConnection();initSelect();initInsert();initDelete();

}// user code end// user code begin {2}// user code end

}

Chapter 10. Enterprise JavaBeans 171

Page 196: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 162. Find an Employee

Update an EmployeeThe updateEmployee method changes a record in the database based on thedata in the employee bean. This method uses the resultSet that was assignedin the findEmployee method. This makes the update step quite simple(Figure 163).

Based on the resultSet from the findEmployee method, the new values for therow are set from the bean. Finally, the resultSet is updated. The resultSet isnot closed in the updateEmployee method; it is closed when the containerinvokes the ejbPassivate method, which calls the close method of theEmployeeStorage class.

public void findEmployee(EmployeeBean empl, String key)throws java.rmi.RemoteException, DataException {

SelectStatement select = new SelectStatement();select.setConnection(dbConn);select.setMetaData(selectMetaData);// Now set the Paramenter for the queryselect.setParameter("EMPNO", key);// and execute the queryselect.execute();// Retrieve the result setresultSet = select.getResult();if (resultSet.getNumRows() == 0)

throw new java.rmi.RemoteException("No Record found");// Now get the resulting column by nameempl.setFirstName(resultSet.getColumnValueToString("FIRSTNME"));empl.setMidInit(resultSet.getColumnValueToString("MIDINIT"));empl.setLastName(resultSet.getColumnValueToString("LASTNAME"));empl.setWorkDept(resultSet.getColumnValueToString("WORKDEPT"));empl.setPhoneNo(resultSet.getColumnValueToString("PHONENO"));empl.setJob(resultSet.getColumnValueToString("JOB"));empl.setSex(resultSet.getColumnValueToString("SEX"));empl.setHireDate((Date)resultSet.getColumnValue("HIREDATE"));empl.setBirthDate((Date)resultSet.getColumnValue("BIRTHDATE"));if (database == 1) { //DB2

empl.setSalary(((Double)resultSet.getColumnValue("SALARY")).doubleValue());empl.setBonus(((Double)resultSet.getColumnValue("BONUS")).doubleValue());empl.setComm(((Double)resultSet.getColumnValue("COMM")).doubleValue());empl.setEdLevel(((Short)resultSet.getColumnValue("EDLEVEL")).shortValue());

}else if (database == 2) { //Oracle

empl.setSalary(((BigDecimal)resultSet.getColumnValue("SALARY")).doubleValue());

empl.setBonus(((BigDecimal)resultSet.getColumnValue("BONUS")).doubleValue());empl.setComm(((BigDecimal)resultSet.getColumnValue("COMM")).doubleValue());empl.setEdLevel(((BigDecimal)resultSet.getColumnValue("EDLEVEL")).

shortValue());}

}

172 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 197: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The method uses a small date2Timestamp method that converts ajava.util.Date object to a java.sql.Timestamp object that is required byOracle. This code is specific to the Oracle database.

Figure 163. Update the Database

Delete an EmployeeThe deleteEmployee method removes the database record with a given key.

public void deleteEmployee(String key) throws DataException {SQLStatement delete = new SQLStatement();delete.setConnection(dbConn);delete.setMetaData(deleteMetaData);// Now set the Parameters for the deletedelete.setParameter("EMPNO", key);delete.execute();

}

public void updateEmployee(EmployeeBean empl) throws DataException {resultSet.setColumnValue("FIRSTNME", empl.getFirstName());resultSet.setColumnValue("MIDINIT", empl.getMidInit());resultSet.setColumnValue("LASTNAME", empl.getLastName());resultSet.setColumnValue("WORKDEPT", empl.getWorkDept());resultSet.setColumnValue("PHONENO", empl.getPhoneNo());resultSet.setColumnValue("JOB", empl.getJob());resultSet.setColumnValue("SEX", empl.getSex());resultSet.setColumnValue("SALARY", new Double(empl.getSalary()));resultSet.setColumnValue("BONUS", new Double(empl.getBonus()));resultSet.setColumnValue("COMM", new Double(empl.getComm()));

if (database == 1) { //DB2Calendar cal = Calendar.getInstance();cal.setTime(empl.getHireDate());java.sql.Date hireDate = new java.sql.Date(cal.get(Calendar.YEAR) - 1900,

cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));resultSet.setColumnValue("HIREDATE", hireDate);cal.setTime(empl.getBirthDate());java.sql.Date birthDate = new java.sql.Date(cal.get(Calendar.YEAR) - 1900,

cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));resultSet.setColumnValue("BIRTHDATE", birthDate);resultSet.setColumnValue("EDLEVEL", new Short(empl.getEdLevel()));

} else if (database == 2) { //OracleresultSet.setColumnValue("HIREDATE",

date2Timestamp(empl.getHireDate()));resultSet.setColumnValue("BIRTHDATE",

date2Timestamp(empl.getBirthDate()));resultSet.setColumnValue("EDLEVEL",

new BigDecimal(Integer.toString(empl.getEdLevel())));}resultSet.updateRow();

}

Chapter 10. Enterprise JavaBeans 173

Page 198: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Testing the Employee BeanBefore testing the employee bean, you have to generate the home and helperclasses. Select EJBs -> Generate -> Deployed Code for the employeeenterprise bean.

Start the EJB ServerAdd the ITSO_EJBs to the server (Add To -> Server Configuration) and startthe server (see “Starting the EJB Server in the Test Environment” onpage 144). Be sure to verify the properties of the server before starting it (seeFigure 134 on page 144).

Test ClientYou can use the test client against the employee bean and retrieve anemployee and update its properties. Generate the test client code (selectGenerate -> Test Client) and start it (see “Using the Test Client” on page 145).

Access the Employee Bean from a ServletFor the employee enterprise bean we created a servlet (EmployeeEJBServlet)that accesses the employee enterprise bean.

The structure of the servlet is exactly the same as the DepartmentEJBServletdescribed in “Access the Department Bean from a Servlet” on page 153,therefore we do not list the complete implementation here.

The servlet consists of the following methods:

❑ init initializes the context and determines the home interface of theemployee bean.

❑ doGet and doPost, which both call the performTask method.

❑ performTask decides whether an employee should be retrieved (invokegetEmployee) or updated (invoke updateEmployee).

❑ findEmployee retrieves an employee bean based on the employee numberby using the home interface of the employee bean.

❑ getEmployee uses findEmployee to retrieve the employee bean and displayit (partially) in an HTML form (Figure 164).

174 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 199: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 164. Retrieve and Display the Employee Bean

public void getEmployee(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);// Get the output writerjava.io.PrintWriter out = response.getWriter();String empNo = getParameter(request, "empNo");out.println("<HTML><HEAD><TITLE>EmployeeEJBServlet </TITLE></HEAD><BODY>");try {

Employee emp = findEmployee(empNo);out.println("<TABLE>" +

"<FORM ACTION = \"/servlet/itso.wasdb.ejb.servlet.EmployeeEJBServlet\">");out.println("<TR>");out.println("<TH>Employee No");out.println("<TH>Firstname");out.println("<TH>Midinit");out.println("<TH>Lastname");out.println("<TH>Phone");out.println("<TH>Salary");out.println("<TR><TD>" + empNo);out.println(" <TD><INPUT TYPE=TEXT NAME=firstName VALUE=\"" +

emp.getFirstName() + "\">");out.println(" <TD><INPUT SIZE=1 TYPE=TEXT NAME=midinit VALUE=\"" +

emp.getMidInit() + "\">");out.println(" <TD><INPUT TYPE=TEXT NAME=lastName VALUE=\"" +

emp.getLastName() + "\">");out.println(" <TD><INPUT SIZE=4 TYPE=TEXT NAME=phoneNo VALUE=\"" +

emp.getPhoneNo() + "\">");out.println(" <TD><INPUT SIZE=11 TYPE=TEXT NAME=salary VALUE=\"" +

emp.getSalary() + "\">");out.println("<TR><TD><INPUT TYPE=HIDDEN NAME=command VALUE=updateEmployee>");out.println("<TD><INPUT VALUE=Update TYPE=SUBMIT>");out.println("</FORM></TABLE>");HttpSession session = request.getSession(true);session.putValue("itso.wasdb.ejb.servlet.EmployeeEJBServlet.employee", emp);

} catch (Exception e) {out.println("<h2>Error: " + e + "</h2>");e.printStackTrace(out);

}out.println("</BODY></HTML>");

}

public Employee findEmployee(String key) throws NamingException, ObjectNotFoundException, RemoteException, FinderException {Employee emp = null;emp = employeeHome.findByPrimaryKey(new EmployeeKey(key));return emp;

}

Chapter 10. Enterprise JavaBeans 175

Page 200: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ updateEmployee sets the properties of the bean based on the input theuser has made in the HTML form (Figure 165).

Figure 165. Set the Properties of the Employee Bean

Testing the ServletStart the WebSphere Test Environment and make sure that the EJB Serveris running. Open a browser and enter the URL:

http://127.0.0.1:8080/servlet/itso.wasdb.ejb.servlet.EmployeeEJBServlet?empNo=000010

The result of the employee servlet looks similar to the department servlet(Figure 166).

Figure 166. EmployeeEJBServlet Output

public void updateEmployee(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {

response.setContentType("text/html");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);// Get the output writerjava.io.PrintWriter out = response.getWriter();out.println("<HTML><HEAD><TITLE>Result</TITLE></HEAD><BODY>");HttpSession session = request.getSession(false);Employee emp = (Employee)

session.getValue("itso.wasdb.ejb.servlet.EmployeeEJBServlet.employee");emp.setLastName(getParameter(request, "lastName"));emp.setFirstName(getParameter(request, "firstName"));emp.setPhoneNo(getParameter(request, "phoneNo"));emp.setMidInit(getParameter(request, "midinit"));emp.setSalary(Double.valueOf(getParameter(request, "salary")).doubleValue());out.println("<H1>Update ok</H1>");out.println("</BODY></HTML>");

}

176 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 201: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Deployment of the Employee Bean to WebSphereThe employee enterprise bean is deployed in the same way as the departmentbean, but there are a few differences:

❑ Export the JAR file (select Export -> EJS Jar). In the export dialog, clickon the Details button and add the EmployeeStorage class. It is required atruntime to access the database. Name the file EmployeeEJS.jar.

❑ In the WebSphere administration dialog for Enterprise Java Services, theglobal settings are fine (Figure 140 on page 150), and we can use the sameITSOContainer (Figure 141 on page 151).

❑ Select the EmployeeEJS.jar file on the EJB Jar Files page (Figure 142 onpage 151) and click on Deploy. Select the ITSOContainer, and click onRedeploy Existing in the warning dialog (Figure 143 on page 152).

❑ Start the test client in VisualAge for Java and connect to the deployedemployee enterprise bean.

Chapter 10. Enterprise JavaBeans 177

Page 202: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

178 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 203: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

11 WebSphere StudioIn this chapter we briefly introduce the WebSphere Studio tools.

We then describe in more detail the servlet generation wizards that alloweasy creation of servlets with relational database access.

© Copyright IBM Corp. 1999 179

Page 204: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

WebSphere Studio ToolsWebSphere Studio can help a Web team build powerful, e-business Web sitespacked with features and interaction, without relying on the CommonGateway Interface (CGI) and Active Server Pages (ASP).

WebSphere Studio combines easy-to-use wizards with site design and Javadevelopment tools, simplifying and speeding the application developmentprocess. It combines graphical development wizards with tools for Web sitedesign and Java development.

These wizards and tools simplify and speed the application developmentprocess, and include:

❑ Web Development Workbench—A Web site project organizer andlaunch platform.

❑ Servlet generation wizards—For building Java servlets to accessJDBC databases and JavaBean components.

❑ VisualAge for Java, Professional Edition V2.0—IBM's Javaapplication development environment for building Java applications,applets, servlets and JavaBean components.

❑ NetObjects Fusion V3.0—Allows Web site developers to design andproduce an entire Web site, including individual pages and all links. Itfeatures automated site building, automatic link management, remotedatabase access, and design and publishing capabilities.

❑ NetObjects BeanBuilder V1.0—The visual authoring tool forcombining JavaBeans and Java applets, BeanBuilder allows individualsoverseeing the content of online business processes to create morecompelling, highly interactive Web sites.

❑ NetObjects ScriptBuilder V3.0—Combines a text-based script editorand development tools for creating and editing HTML, script, andJavaServer Pages (JSP).

In this chapter we only cover the servlet wizards and show how to use themto create simple database access servlets, the corresponding JSPs, andJavaBeans.

180 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 205: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Installation and ConfigurationDuring our work we used WebSphere Studio 3.0 Beta 2 which wasdownloadable from http://www.software.ibm.com/webservers/.

Although WebSphere Studio allow the specification of a class path, it seemsto be important to put any class files, for example, db2java.zip for DB2 orclasses111.zip for Oracle, in the system class path. Before you startWebSphere Studio make sure the necessary zip/jar files are in the class path(Control Panel -> System -> Environment -> CLASSPATH).

The next important point is to specify where WebSphere Studio stores thepublished files. Usually this is the place where the WebSphere ApplicationServer resides. Unfortunately one cannot change the preferences withouthaving a project open. That is the reason why we come back to this point in“Publish the Project” on page 194.

The examples described here are provided as archive files. To open them,select File -> Open Archive from the menu and select the Itso.war file fromthe Studio directory. Replace the content of the ITSO project with the extractof the Itso.war file.

Project SetupThe development of Web sites is organized in projects in WebSphere Studio.Naturally the first step is to create a new project that will be our playground.When WebSphere Studio is started the first time, it asks whether it shouldcreate a new project, use an existing project or exit.

❑ We want to create a new project. So click Create new in the first dialog(Figure 167).

Figure 167. Create New Project

❑ Now specify the name ITSO for the project (Figure 168).

Chapter 11. WebSphere Studio 181

Page 206: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 168. Specify Project Parameters

❑ You should now have a project window (Figure 169).

Figure 169. WebSphere Studio Project Window

182 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 207: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Create an SQL Statement and ServletTo compose a database query and let WebSphere Studio create a servlet, weuse the SQL Wizard:

❑ Select the project ITSO on the left side.

❑ From the tool bar select SQL Wizard (Figure 170).

Figure 170. WebSphere Studio Tool Bar

❑ In the SQL Wizard dialog you have to provide a name for the SQLstatement. In this example we want to select employees and some datafrom their department from the database. The records will be selected bypartial employee last names. Therefore we name the new SQL statementEmplDepByEmplName (Figure 171).

Figure 171. Specify a Name for the SQL Statement

Chapter 11. WebSphere Studio 183

Page 208: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ The next step is to provide the wizard with the necessary databaseconnection information (Figure 172). As usual, we provide the followingfor DB2:

• Driver: IBM DB2 UDB local (COM.ibm.db2.jdbc.app.DB2Driver)

• URL: jdbc:db2:itsowdb

• User ID and password: ITSO and itso (as in all examples)

To close the dialog, we click on Connect.

Figure 172. Specify the Connection Parameters

Note: For Oracle you would specify jdbc:oracle:thin:@localhost:1521:orclfor the database URL and Oracle for the driver. For SQL Server you wouldspecify jdbc:odbc:SQLServer for the database URL and JDBC-ODBCBridge for the driver.

❑ On the Tables page select the two tables, department and employee, of thedatabase (Figure 173) and click Next.

184 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 209: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 173. Select Tables from the Database

❑ On the Join page, specify an inner join by selecting DEPNO in thedepartment table and WORKDEPT in the employee table and click onJoin (Figure 174).

Figure 174. Specify the Join

Chapter 11. WebSphere Studio 185

Page 210: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ On the Columns page we select the columns to display (Figure 175).During the time this book was written, the data access bean seemed tohave problems with date fields (see “Data Access Beans” on page 266). Toavoid trouble for the time being, it is better not to select a date field.

Figure 175. Specify the Columns to Display

❑ On the Condition 1 page we specify the condition for the select statement(Figure 176).

Select the EMPLOYEE table, the LASTNAME column and the containsthe character(s) operator. Now we have to enter a host variable for thevalue of the condition. We click on the first text field and then on theParameter button. A dialog to name the parameter pops up and we enterlastName. Parameter values are displayed in bold face in the text fieldwhereas fixed values are displated normal.

This specification generates a WHERE clause of the format:

LASTNAME LIKE '%'||?||'%'

186 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 211: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 176. Specify the Conditions

❑ Because we do not want to sort the output we can now view the completeSQL statement (Figure 177) and then generate the code by clicking on theFinish button.

Figure 177. Completed SQL Statement

The WebSphere project window now contains a new file namedEmplDepByEmplName.sql. This file is the basis for the next step, that is, tocreate a servlet that accesses the database using this SQL statement and tocreate the corresponding JavaServer Pages that provide the input and outputfor the servlet.

SELECT ITSO.EMPLOYEE.FIRSTNME, ITSO.EMPLOYEE.LASTNAME, ITSO.EMPLOYEE.PHONENO,ITSO.EMPLOYEE.JOB, ITSO.EMPLOYEE.SALARY, ITSO.DEPARTMENT.DEPTNAME

FROM ITSO.DEPARTMENT, ITSO.EMPLOYEEWHERE ( (ITSO.EMPLOYEE.WORKDEPT = ITSO.DEPARTMENT.DEPTNO) AND

(ITSO.EMPLOYEE.LASTNAME LIKE '%'||?||'%') )

Chapter 11. WebSphere Studio 187

Page 212: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Create the Servlet and JSPsThe SQL query is ready and can be used in the Database Wizard to create aservlet and a JSPO. Select the Database Wizard from the tool bar (Figure 170on page 183) or from the menu.

❑ We only have one query so far, EmplDepByEmplName.sql. It should beselected by default, if not select it from the combobox (Figure 178). ClickNext.

Figure 178. Select the SQL Statement

❑ The next step is to select what Web pages should be created (Figure 179).Because WebSphere Studio 3 beta 2 and WebSphere Application server2.0.2 are a little inconsistent at the moment, you should not use the lastoption. For an explanation see “WebSphere Studio” on page 267. ClickNext.

188 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 213: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 179. Select the Generated Pages

❑ Now we specify the parameters that will appear on the input page. Weneed at least the lastName parameter (Figure 180). Click Next.

Figure 180. Specify Input Parameters

Chapter 11. WebSphere Studio 189

Page 214: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ This next step is similar, but specifies the parameters for the resultingoutput page (Figure 181). We select all the table columns, but are notinterested in the database driver, URL, SQL statement, and user ID,although this might be useful for testing purposes. Click on Next.

Figure 181. Specify the Fields for the Result Page

❑ In the next step you may add your own error message or you might evenspecify your own error page. We do not have our own error handling fornow, and therefore we use the default.

❑ The next step is to select which methods of the generated JavaBean haveto invoked and in what order. Because we only have one method, theexecute method, we do not change anything. The execute method does theactual query.

❑ Now we may specify whether the query is used in more than one outputpage. If so, this step enables us to attach the bean to an HttpSessionobject, which is then accessible by more than just the direct JSP outputpage.

If multiple output pages are not selected, the resulting bean is just part ofthe request object and is only accessible from the JSP result page of thegenerated servlet.

For this simple example we do not select multiple output pages (Figure182).

190 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 215: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 182. Specify to Use the Bean in a Session

❑ The last step is to give more detailed information to the servlet generatorregarding the Java package (itso.wasdb.studio) and the name of the file.To provide that information, click the Advanced button in the Finishdialog and provide the package name and the prefix (Figure 183).

Figure 183. Provide Package Name and Class Name Prefix

❑ The Finish dialog is shown in Figure 184. Click the Finish button.

Chapter 11. WebSphere Studio 191

Page 216: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 184. Finish the Wizard

Project View after the Database WizardThe project view should now show a few more files (Figure 185).

Figure 185. Project after Servlet Generation

192 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 217: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Here is a description of the newly generated files:

❑ EmplDepByEmplName.java and EmplDepByEmplName.class arethe Java source and class files for the bean that represents the actualdatabase query. The bean uses the IBM data access bean and the IBMconnection manager to access the database. It offers several methods; themost important one is the execute method, which performs the query.Moreover, for each output column selected in Figure 181 on page 190, itoffers a getCOLUMN_NAME method, which returns the particular valuefor that column of the query.

❑ EmplDep.java and EmplDep.class are the Java source and class filesfor the generated servlet. The servlet is derived from the PageListServletclass. That means the pages that are called from this servlet are nothard-coded, but specified in the servlet configuration fileEmplDepServlet.servlet. The most important method is the performTaskmethod. It reads parameters from the servlet configuration file (user ID,password, database driver, URL). It also reads the input parametersspecified in Figure 180 on page 189 from the request, initializes thedatabase bean EmplDepByEmplName with the necessary parameters,and invokes its execute method. Additionally, it adds the instance of theEmplDepByEmplName bean to the request, then calls the outputJavaServer Page.

❑ EmplDepServlet.servlet is an XML-based configuration file that sets therules for the servlet. It regulates which page is to call when the servlethas successfully accessed the database, and also which page is to invokein case of an error or in case no data was found. Furthermore, it containskey/value pairs for the user ID, the password, the database driver, and theURL.

❑ EmplDepInputPage.html is an HTML simple input page that enablesthe user to enter a value for the lastName parameter and then invokes theEmplDep servlet.

❑ EmplDepResultPage.jsp is the JavaServer Page that is called from theservlet after successfully accessing the database. To display the results ituses the EmplDepByEmplName bean that was instantiated by the servletand given to this page through the request block.

❑ EmplDepErrorPage.jsp is the JavaServer Page that is called in case ofan error.

Chapter 11. WebSphere Studio 193

Page 218: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Publish the ProjectThe final step for this sample servlet is to deploy all the generated files to theWebSphere application server, that is, to publish the files to the server.

We have to make sure that WebSphere Studio publishes the files to theproper directories for the HTTP Server and WebSphere. If you have used adefault installation, WebSphere searches for servlets under:

c:\WebSphere\AppServer\servlets

and the IBM HTTP Server is looking for HTML files in:

c:\Program Files\IBM HTTP Server\htdocs

Publishing ConfigurationsThere are three possible configurations between WebSphere Studio andWebSphere Application Server:

❑ In case WebSphere Studio and the WebSphere Application Server are onthe same machine, we check that the publishing properties of the serverare correct. We switch to the publishing view in the project window byselecting View -> Publishing, or alternatively by clicking the appropriateicon from the tool bar. Open the properties from the context menu of theserver (Figure 186).

Figure 186. Specify Publishing Options

In the properties dialog, click on the Default Publishing Target button(Figure 187). Make sure the sure the targets match your configuration.

194 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 219: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 187. Publishing Server Properties

❑ In case WebSphere Studio and the WebSphere Application Server are ondifferent Windows machines but the machine with the Application Serveris accessible as a shared drive, the publishing is almost the same, exceptfor the fact that the server name is not localhost. You may specify this alsoin the server properties dialog (Figure 187).

❑ In case the WebSphere Application Server is on a machine that is notaccessible as a shared drive, use an FTP upload mechanism to publish thefiles to the application server. Again the server properties dialog (Figure187) is the place to detail the FTP parameters.

Once the publishing configuration is specified, we can publish the files to theApplication Server and the HTTP Server. From the context menu of theserver http://myserver select Publish this Server. In the first dialog that isdisplayed you may specify additional options. For our example, no changesare required. In the next dialog we can select the files to be published; thedefault selection is correct for this step as well.

Chapter 11. WebSphere Studio 195

Page 220: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Assembly StagesWebSphere Studio has two predefined assembly stages, test and production.Select View -> Assembly Stage to switch between the two stages.

You can define the test assembly stage for local publishing (localhost) and theproduction assembly stage for publishing to another Web server. Set up theproperties and publishing targets for both assembly stages.

Publishing TargetsThe publishing target dialog defines the two directories for publishingHTML/JSP files and servlet classes (Figure 188).

Figure 188. Publishing Targets

196 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 221: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Testing the Generated ServletTesting is easy and straightforward once the project has been published toWebSphere. From the context menu of the EmplDepInputPage.html fileselect Preview -> netscape or iexplore depending on the favorite browser(Figure 189).

Figure 189. Select Preview from the Context Menu

The HTML input page is plain but functional (Figure 190).

Figure 190. Generated HTML Input Page

Chapter 11. WebSphere Studio 197

Page 222: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The HTML output page that is generated by the JSP displays the result ofthe simple servlet (Figure 191).

Figure 191. Generated HTML Output Page

Enhanced Insert ExampleIn the second example we will develop a simple servlet that inserts a newemployee in the database. With the help of the Studio Wizards this is also avery simple process. In the second step we will enrich the input page of theinsert servlet so that it already shows all available department numbers in acombobox. Because the department number is a foreign key in the employeetable, this assures that only existing values will be inserted.

Create an SQL StatementThe first step is to create an SQL statement with the SQL Wizard:

❑ Name the SQL statement InsertEmployee.

❑ Provide the connection parameters.

❑ Select the employee table and make sure you select Insert for the SQLtype (Figure 192).

198 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 223: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 192. Creating an Insert Statement

❑ Select the columns that are inserted. The columns with the bluebackground are not null columns in the table, therefore they aremandatory (Figure 193). In addition to the mandatory fields we select thePHONENO and the WORKDEPT field.

Figure 193. Select the Input Fields

Chapter 11. WebSphere Studio 199

Page 224: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ The resulting SQL statement is shown in Figure 194.

Figure 194. Generated SQL Insert Statement

Create a ServletWith the SQL statement specified, the next step is to create a servlet basedon that statement. We use the Database Wizard:

❑ Select the InsertEmplyee.sql statement that was just created.

❑ Create an input and result page.

❑ Select the input fields empNo, firstName, midInit, lastName, edLevel,phoneNo, and workDept. You might also want to sort them using the upand down arrows on the right side.

❑ Select columns for the results page, for example firstName and lastName.

❑ Select the execute Method in the next step.

❑ We do not use the bean in more than one page, so no change is necessaryin the next dialog.

❑ Finally specify the advanced parameters, that is, the package nameitso.wasdb.studio and a meaningful prefix, for example InsertEmpl.

❑ Click Finish to generate the code.

❑ Publish the project.

Viewing the ResultThe input page is shown in Figure 195. Notice that the user is allowed tospecify any working department number regardless of whether thedepartment exists or not.

It would be nice to enhance this process to allow the user to select onlyexisting department numbers. This is what we will do next.

INSERT INTO ITSO.EMPLOYEE ( EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, EDLEVEL ) VALUES ( ?, ?, ?, ?, ?, ?, ? )

200 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 225: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 195. Insert a New Employee

Determine all Available Department NumbersTo enhance the input form with a combobox that displays all the availabledepartment numbers, we create an SQL statement to retrieve them.

This step is quite easy with the SQL Wizard:

❑ Create a new SQL statement named AllDepNumbers.

❑ Provide the connection parameters.

❑ Select the department table.

❑ Select the DEPTNO column to include (Figure 196).

❑ That is all. Click Finish.

Chapter 11. WebSphere Studio 201

Page 226: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 196. Select the DEPNO Column

Based on this statement, we create a servlet using the Database Wizard.

❑ Although we actually do not need input and output pages, we will createan output page because the PageListServlet class apparently requires it.Later, when the servlet is created, we will modify the source slightly, sothat no output page is called and we can also delete the output page.

❑ Continue to the session step. Give the bean a meaningful name, forexample, change it from BeanAlias to depNumbers.

❑ Continue to the end; no changes should be necessary. Specify as usual thepackage itso.wasdb.studio and the prefix AllDepNumbers, and finish thewizard.

Invoke the Servlet from a JSPWe want to use the servlet we just created as an input for the page where wespecify the new employee, that is in the InsertEmplInputPage.html. We usethe HTML page as a base and modify it and create a JSP file.

Open the page by double clicking on it. The WebSphere Studio Page Designeris started (Figure 197). This is the HTML/JSP editor of WebSphere Studio.We will not provide an introduction in the usage of this editor, but you canuse it to enhance the generated input and output pages.

We will use the editor to add the invocation of a servlet, the AllDepNumbersservlet, and at the same time add the bean that is created by theAllDepNumbers servlet. This process makes it possible to use the bean tocreate a combobox that holds all the possible department numbers retrievedby the database query.

202 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 227: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 197. WebSphere Page Designer

❑ Start by adding a servlet invocation to the top of the page. Use the menuInsert -> Servlet. In the dialog specify the name of the servlet to beinvoked, in our case the AllDepNumbersServlet (Figure 198). Enteritso.wasdb.studio.AllDepNumbersServlet as the code attribute.

Figure 198. Specify the Servlet to be Invoked

Chapter 11. WebSphere Studio 203

Page 228: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

This specification generates the code

<SERVLET code="itso.wasdb.studio.AllDepNumbersServlet"></SERVLET>

❑ The next step is to insert the bean, also at the top. Select Insert -> JSPTags -> Bean Tag from the menu. The name of the bean is depNumbers(the name we gave a few steps earlier) and the type of the bean isitso.wasdb.studio.AllDepNumbersBean (Figure 199).

Figure 199. Specify Bean Parameters

This specification generates the code

<BEAN name="depNumbers" type="itso.wasdb.studio.AllDepNumbersBean"></BEAN>

❑ Delete the last text field (the working department) and substitute it witha combobox. The result page should now contain one servlet tag, one beantag, and a combobox instead of a text field (Figure 200).

204 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 229: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 200. Resulting Page

❑ Next, you have to provide the possible values for the combobox that aredynamically retrieved by the AllDepNumbers servlet.

Double-click on the combobox and specify the name workDept in thedialog. This is the name the text field had when we specified it with thedatabase wizard (Figure 193 on page 199).

❑ In the same dialog switch to the Dynamic pane. This is the place toprovide the combobox with possible values.

To retrieve the values dynamically, we select the Loop Property and clickon Browse. Another dialog is displayed where we can browse the availableproperties of all the beans accessible from this page (Figure 201). Browsethe depNumbers bean and select the ITSO_DEPARTMENT_DEPTNOproperty.

❑ On the same page specify the Item Property that is displayed in thecombobox. In this case it is the same as the loop property (Figure 201).

Select Specify as Property and browse once more to theITSO_DEPARTMENT_DEPTNO property. If we had specified more thanone output field in the Database Wizard (for example, the departmentname), such fields could also be used here.

Servlet and Bean

Combobox

Chapter 11. WebSphere Studio 205

Page 230: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 201. Selecting the Loop Property

❑ Switch to the Html Source view and look at the generated code for thistable cell (Figure 202).

The first cell of the table row contains the word workDept. The next cellcontains the dynamic content that is evaluated and replaced by theWebSphere Application Server at runtime. Basically, we specified whichproperty is iterated and which property is displayed as a value. In ourcase, both are the same property.

206 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 231: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 202. Generated Code for Dynamic Item Values

Everything is ready. You might want to enhance the look of the page. Also,you might want to inspect the generated JSP and HTML code.

Save the Modified HTML Page as a JSPBecause we imbedded Java logic into the HTML page, we have to execute thepage as a JSP.

Save the page (File -> Save As) as InsertEmplInputPage.jsp and select Add toWebSphere Studio in the save dialog. The Beta 2 product complains with anerror message that this is not possible and then asks you to save again. Justsave again, and although WebSphere Studio complained, everything worksfine.

Modify the Generated ServletThe final step is to modify the generated source of the AllDepNumbersservlet. The servlet is generated by WebSphere Studio and by default it isderived from the PageListServlet.

A PageListServlet is configurable by the matching servlet XML configurationfile (AllDepNumbersServlet.servlet). This configuration file contains someparameters for the servlet, such as the database user ID, password, the

<TR><TD>workDept</TD><TD> <!--METADATA type="DynamicData" startspan <SELECT dynamicelement loopproperty="depNumbers.ITSO_DEPARTMENT_DEPTNO()" itemproperty="depNumbers.ITSO_DEPARTMENT_DEPTNO()" name="workDept" </SELECT> --><% try { java.lang.String _p0 = depNumbers.getITSO_DEPARTMENT_DEPTNO(0); %><SELECT name="workDept"><% for (int _i0 = 0; ; ) { %> <OPTION><%= _p0 %></OPTION><% _i0++; try { _p0 = depNumbers.getITSO_DEPARTMENT_DEPTNO(_i0); } catch (java.lang.ArrayIndexOutOfBoundsException _e0) { break; } } %> </SELECT><% } catch (java.lang.ArrayIndexOutOfBoundsException _e0) { } %><!--METADATA type="DynamicData" endspan--> </TD></TR>

Chapter 11. WebSphere Studio 207

Page 232: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

driver, and the URL. It also specifies which output page is the default resultpage for the servlet, which page is the error page, and all the other possibleoutput pages.

In our case, we do not want an output page called by the servlet. For thisreason, we change the source code of the servlet:

❑ Open the Java source file of the servlet, that is, AllDepNumbers.java. Ithas several methods; the most important one is the performTask method.At the very end of this method, you will find the following line:

callPage(getPageNameFromRequest(request), request, response);

Comment it out. The effect is simple. The output JSP page we hadconfigured is not called anymore.

This is exactly what we would like to achieve, because the servlet isalready called from a JSP and the output of the servlet is the depNumbersbean, which is included in the output JSP.

❑ Save the file and select Compile from the context menu in WebSphereStudio.

❑ Finally select the server and publish the project to the server.

Test the JSP and the Servlet in WebSphereAfter publishing the code to the WebSpere Application Server we can test theJSP and the servlet.

Select Preview -> iexplore or navigator from the context menu of theInsertEmplInputPage.jsp from the Publish view. As you can see in thebrowser, the working department now contains a combobox with all availabledepartment numbers (Figure 203).

Problem with Servlet ConfigurationThe JSP calls the AllDepNumbers servlet. When loaded, the code looks forthe servlet configuration file, AllDepNumbers.servlet, but the generated fileis named AllDepNumbersServlet.servlet.

We copied the AllDepNumbersServlet.servlet file as AllDepNumbers.servletand deployed that copy into the same directory.

Note: We also tried to call the servlet by the name AllDepNumbersServlet(Figure 198 on page 203), but then the load of the servlet from the JSPservlet failed completely.

208 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 233: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 203. Enhanced Insert Servlet Input Page with Combobox

Chapter 11. WebSphere Studio 209

Page 234: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Debugging the Servlets in VisualAge for JavaHere are the steps required to debug the generated servlets in VisualAge forJava.

❑ As a prerequisite, the ITSOWDB database must be available andaccessible through the same JDBC drivers, URL, user ID, and passwordas specifed for WebSphere.

❑ Import the six servlet source and bean files (.java) into the ITSO SG245471 project in VisualAge for Java. The itso.wasdb.studio package iscreated.

❑ Error messages are reported for each servlet.

import comm.ibm.webtools.runtime.*; <=== missing package

This package is not required, therefore you can delete the line from eachservlet.

❑ Copy the HTML and JSP files to the proper HTML directory. If youperformed a local publishing, the files should be there already.

❑ Copy the servlet configuration files (.servlet) into the resources directory:

c:\IBMVjava\ide\project_resources\ITSO SG24 5471\itso\wasdb\studio

Make sure that you have the AllDepNumbers.servlet file (copy ofAllDepNumbersServlet.servlet).

❑ Start the WebSphere Test Environment and open a browser with theURL:

http://127.0.0.1:8080/EmplDeptInputPage.htmlhttp://127.0.0.1:8080/InsertEmplnputPage.jsp

❑ You can set breakpoints in the servlet code to activate the debugger.

210 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 235: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Hints and Tips for WebSphere StudioThe beta code of WebSphere Studio has some problems that may disturbsmooth operation. Here are a few pointers on how to deal with problems.

Synchronization between Development and Publishing ViewIt seems that sometimes files of the development view (left side of the projectview) do not show up in the publishing view (right side). The Sync left viewand right view push button in the tool bar does not work (Figure 204).

You can force a file to the publishing view by selecting it, open its properties,and on the Publishing page deselect the Set publishable checkbox. Click OK.Then open the properties again, select the checkbox, and click OK. Thiscopies the file to the publishing view.

CheckoutFiles that have been edited have the checkout flag (a red check mark). Youcan select the file and select Check In from the context menu.

In the directory structure, checked out files are in the directory:

c:\WebSphere\StudioBeta\check_out\..projectname...

Files that are checked in are marked read-only in the directory:

c:\WebSphere\StudioBeta\projects\..projectname...

Publishing Warnings About Old Class FilesWhen publishing, we got a warning message that the class file (.class) wasolder than the source file (.java). In such situations you can check out thesource and class files and compile the source file (select Compile from thecontext menu). After that check both files in.

Mismatch between Servlet and Servlet ConfigurationFor a servlet called from a JSP, the naming of the servlet (.java) and servletconfiguration file (.servlet) does not work. See “Problem with ServletConfiguration” on page 208 for a circumvention.

Chapter 11. WebSphere Studio 211

Page 236: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Project ViewFigure 204 shows our project view after completing all the samples.

Figure 204. Complete Project View

212 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 237: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

12 WebSphere UserProfileIn this chapter we describe the user profile function of WebSphere. We alsodevelop a sample servlet utilizing the user profile function.

© Copyright IBM Corp. 1999 213

Page 238: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DescriptionThe WebSphere Application Server includes classes in thecom.ibm.servlet.personalization.userprofile package that make it easier tomaintain persistent information about your Web site visitors and use thatinformation to customize your Web pages.

At the time of the release of the WebSphere, the classes of the packagecom.ibm.servlet.personalization.userprofile are considered a referenceimplementation, because issues, such as database schema and runtimeenvironments, can vary greatly from application to application. Given theseconsiderations, WebSphere includes the source of the UserProfile class andan example of how to extend the class. Both source files are in theWebSphere\AppServer\samples\userprofile directory. The only coupling betweenthe UserProfile class and the rest of WebSphere is that the UserProfile classand IBM's session implementation (IBMSessionData) have a user name fieldthat can be used to create some synergy between the two classes.

The UserProfile class includes data members for a visitor's complete name,postal and e-mail addresses, and telephone numbers, and has fields to storelanguage of choice, employment, and user-defined group information. Inaddition, it has a generic message, a shopping cart, and a clipboard that is aJava hash table. This allows you to easily incorporate other objects of yourchoice into these data members and handle them as part of the UserProfileclass. Because these objects are persistent across successive instantiations ofthe UserProfile, they must be serializable. If you use a JDBC database, theobjects will be stored in the database. Otherwise, they will be stored as files.In the WebSphere Application Server Version 2.0, the UserProfile class usesthe database connection manager to maintain JDBC connections.

ConfigurationTo set up the user profile function, you should use WebSphere’sadministration dialogs. Once you have started the administration program(see “WebSphere Configuration” on page 6), select Setup -> UserProfile.

Enable PageOn the Enable page select yes for Using UserProfile? (Figure 205). As you cansee the UserProfile class itself can be modified. So if your application hassome specific needs where it requires modifying the code, you can do so andcan place the modified class name in here.

214 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 239: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 205. Enabling User Profile

Database PageThe database information required here is based on the URL used for theJDBC connection. Every database server has its own URL and each differsfrom the other. The way in which the UserProfile uses the information is asfollows:

URL: jdbc:" + Config.DBUSED + ":" + Config.DB_NAME;

Table Name: Config.DB_OWNER + "." + Config.USER_TABLE

Figure 206 shows the specification for DB2, Figure 207 for Oracle, and Figure208 for SQL Server.

Chapter 12. WebSphere User Profile 215

Page 240: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2

Figure 206. UserProfile Database Setup for DB2

Oracle

Figure 207. UserProfile Database Setup for Oracle

216 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 241: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SQL Server

Figure 208. UserProfile Database Setup for SQL Server

Connection Manager PageOn the ConnMgr (connection manager) page you select the pool with respectto the database you have selected on the Database page (Figure 209).

Figure 209. UserProfile’s Connection Pool Selection

Chapter 12. WebSphere User Profile 217

Page 242: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Click on Save and log off. The changes for the user profile only take effectwhen you stop the Web server and WebSphere. Then restart the Web server.

The UserProfile table is created the first time an attempt is made to accessthe user profile function.

User Profile Create, Update and RetrieveIn this section we briefly describe how to create, update, and retrieve the userprofile from the database to provide you with some understanding on how theuser profile works.

CreateCreating the user profile using new UserProfile() does not result in writingthe user profile into the database. To create an entry in the database tableuse insertToDatabase(UserProfile userProf). When using theinsertToDatabase method, the UserProfile passed to it must already have theUserName property set up, because there is no method for setting theUserName. Therefore you cannot call new UserProfile() and then pass thenewly created class to the insertToDatabase method.

The way to create a UserProfile would be using the static methodaddUserProfile. This method has three variations, which are:

❑ UserProfile addUserProfile(String userName)

In this method the userName is directly passed, and the returnedUserProfile does contain the userName. You can set the rest of theparameters using the setter methods available in the UserProfile class.

❑ UserProfile addUserProfile(HttpSession httpSession)

In this method the session object is expected to have a parameter calleduserName of type String. This can be done with a method call such ashttpSession.putValue("userName",userName). Once the userName isextracted from the session, addUserProfile(userName) is called to create aUserProfile. From this point on, other parameters are extracted from thesession, if any of them is set, and the appropriate setter method is called.

Note: The extraction of parameters from the session and calling the settermethods is done behind the scene.

❑ UserProfile addUserProfile(HashTable clipboard)

In this method the hash table object is expected to have a parametercalled userName of type String. This can be done with a method call such

218 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 243: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

as clipboard.put("userName",userName). Once the userName is extracted,the addUserProfile(userName) is called. After that point, otherparameters are extracted and the appropriate setter method is called.

Note: The extraction of parameters from the hash table and calling thesetter methods is done behind the scene.

The second and third methods are merely wrappers functions that call thefirst method.

UpdateYou can update all of the fields except the userName in a UserProfile object:

❑ void updateUserProfile(HttpSession sess)

In this method the session object is expected to have a parameter calleduserName of type String.

❑ void updateUserProfile(Hashtable clipboard)

In this method the hash table object is expected to have a parametercalled userName of type String.

RetrieveThere are several ways to retrieve a UserProfile object:

❑ UserProfile retrieveUserProfileByUserName(String userName)

Based on the userName the UserProfile is returned.

❑ UserProfile retrieveUserProfile(String type, String key)

type is the column name in the UserProfile table and key is the value ofthe column.

❑ Enumeration retrieveUserProfiles(String type, String key, Statement s)

In this method a statement is assembled based on the type and methodreturned. The results are 0 or multiple user profiles returned through anEnumeration object.

There are several other methods in the UserProfile class that can be used toretrieve the UserProfile based on different properties, for example,retrieveUserProfilesByLanguage.

Chapter 12. WebSphere User Profile 219

Page 244: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

UserProfile ExampleIn this example we want to demonstrate how the UserProfile is created andaccessed. Also the usage of a shopping cart in the UserProfile context isdiscussed.

Classes and MethodsIn this example we have employed JavaBean, JSP, and Servletmethodologies. The package itso.wasdb.userprofile contains the classes usedin this example. The following is the list of classes (Figure 210).

Figure 210. itsowasdb.userprofile Class Listing

ItemItem is a JavaBean class that is passed as a shoppingCart object to aUserProfile. The properties are:

String item; /* name of the item */String price; /* price of the item */

An ItemBeanInfo class is generated by VisualAge for Java when the Itemclass is created.

UserCartUserCart is a JavaBean class that contains the basic information used tocreate a UserProfile. The properties are:

String language;String firstName;String midName;String lastName;String userName;

A UserCartBeanInfo class is generated by VisualAge for Java when theUserCart class is created.

220 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 245: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Note: The two classes Item and UserCart are simple Java Bean classes withgetter and setter methods. We will not describe these classes in detailbecause they do not need further explanation.

UserProfileCartServletThe UserProfileCartServlet class handles all of the incoming requests andoutgoing responses. It is within this class where all of the transactions takeplace. Figure 211 shows the methods of the UserProfileCartServlet class.

Figure 211. UserProfileCartServlet Methods Listing

The UserProfileCartServlet class manages the access to the user profile. Itcreates a user profile if it does not exist and displays the contents for anexisting user profile. The content of the shopping cart of the profile ismodifiable. Our class is a subclass of PageListServlet, which is a subclass ofHttpServlet that can invoke JSPs (Figure 212).

Figure 212. UserProfileCartServlet Class Declaration

The addUserShoppingCart method adds the shopping cart object into theUserProfile (Figure 213).

import javax.servlet.*;import javax.servlet.http.*;import com.ibm.servlet.personalization.userprofile.*;

public class UserProfileCartServlet extends com.ibm.servlet.PageListServlet implements java.io.Serializable

{ private UserProfile profile = null;

}

Chapter 12. WebSphere User Profile 221

Page 246: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 213. UserProfileCartServlet addUserShoppingCart Method

Note: In our simple example, the shopping cart contains only one item. Tomake this a true shopping cart, you can pass a Vector that contains multipleobjects. Any collection type of object can be placed here as long as all of thecollection objects and the objects inside of them are Serializable.

The createUserProfile method checks to see if the profile already exists underthe specified UserName. If not, it will create and update the UserProfilefields. If there is a UserProfile under the same UserName it throws anexception (Figure 214).

Figure 214. UserProfileCartServlet.createUserProfile

The doGet method processes incoming HTTP GET requests (Figure 215).

Figure 215. UserProfileCartServlet doGet Method

public void addUserShoppingCart(Item item) throws java.io.NotSerializableException {

profile.addShoppingCart(item);}

public void createUserProfile(UserCart userCart) throws java.lang.Exception {

profile = UserProfile.addUserProfile(userCart.getUserName());

if( profile != null) {profile.setFirstName(userCart.getFirstName());profile.setLastName(userCart.getLastName());profile.setLanguage(userCart.getLanguage());

}else {

throw new java.lang.Exception("UserName: " + userCart.getUserName()+ " already exists");

}}

public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {

performTask(request, response);}

222 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 247: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The doPost method processes incoming HTTP GET requests (Figure 216).

Figure 216. UserProfileCartServlet doPost Method

The getParameter method reads a parameter from the HTML or JSP file andreturns it as a string (Figure 217).

Figure 217. UserProfileCartServlet getParameter Method

public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {

performTask(request, response);}

public String getParameter(HttpServletRequest request, String parameterName, boolean checkRequestParameters, boolean checkInitParameters, boolean isParameterRequired, defaultValue) throws java.lang.Exception {

java.lang.String[] parameterValues = null;java.lang.String paramValue = null;

// Get the parameter from the request object if necessary.if (checkRequestParameters) {

parameterValues = request.getParameterValues(parameterName);if (parameterValues != null)

paramValue = parameterValues[0];}// Get the parameter from the servlet init parameters if// it was not in the request parameter.if ( (checkInitParameters) && (paramValue == null) )

paramValue = getServletConfig().getInitParameter(parameterName);

// Throw exception if the parameter was not found but was requiredif ( (isParameterRequired) && (paramValue == null) )

throw new Exception("Parameter" + parameterName + "was not specified.");

// Set the return to the default value if the parameter was not foundif (paramValue == null) paramValue = defaultValue;

return paramValue;}

Chapter 12. WebSphere User Profile 223

Page 248: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The itemCreateToOutputPage method takes care of creating an item andadding it to the UserProfiles shopping cart. Once the update is donesuccessfully, the output page (a JSP) is called to display UserProfile and itsshopping cart content (Figure 218). This method is invoked when the Submitbutton from the ItemCreate page (Figure 226 on page 229) is clicked.

Figure 218. UserProfileCartServlet itemCreateToOutputPage Method

The performTask method processes incoming requests for information. Itchecks from which page the request has been made and, based on thatinformation, calls the appropriate method (Figure 219). In case any of themethods called throw an exception, the handleError method is called, whichin turn launches the error output page (Figure 233 on page 234).

public void itemCreateToOutputPage(HttpServletRequest request,

HttpServletResponse response, UserCart userCart , Item itemInfo) throws java.lang.Exception {

UserCart tempCart = null; javax.servlet.http.HttpSession session = null;

session = request.getSession(true);itemInfo.setItem(getParameter(request,"item", true, true, true, null));itemInfo.setPrice(getParameter(request,"price", true, true, true, null));tempCart = (UserCart)session.getValue("userCart");

userCart.setFirstName(tempCart.getFirstName());userCart.setLastName(tempCart.getLastName());userCart.setUserName(tempCart.getUserName());userCart.setLanguage(tempCart.getLanguage());

addUserShoppingCart(itemInfo);

//default output pagecallPage(getPageNameFromRequest(request), request, response);

}

224 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 249: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 219. UserProfileCartServlet performTask Method

public void performTask(HttpServletRequest request, HttpServletResponse response) {

try {

// instantiate the bean and store it in the request so it can be accessed by // the called pageUserCart userProfileCart = null;Item itemInfo = null;String aPageName = new String();

itemInfo = (Item) java.beans.Beans.instantiate(getClass().getClassLoader(), "itso.wasdb.userprofile.Item");

userProfileCart = (UserCart) java.beans.Beans.instantiate(getClass().getClassLoader(),

"itso.wasdb.userprofile.UserCart");// store the bean in the request so it can be accessed // by pages which are accessed with callPage()

setRequestAttribute("userProfileCart", userProfileCart, request);setRequestAttribute("itemInfo", itemInfo, request);

aPageName = getParameter(request, "PageName", true, true, true, null);

if(aPageName.compareTo("ItemCreate") == 0) {itemCreateToOutputPage(request, response, userProfileCart, itemInfo);

}else if(aPageName.compareTo("UserOutput") == 0) {

callPage("ItemCreate", request, response);}else if(aPageName.compareTo("UserCreate") == 0) {

userCreateToOutputPage(request, response,userProfileCart);}else { //request is from "Login" page

userProfileCart.setUserName(getParameter(request, "userName", true, true, true, null));

processLogin(request, response, userProfileCart, itemInfo);}

}catch (Exception theException){

handleError(request, response, theException);try{

java.io.PrintWriter out = response.getWriter();out.println("_____________________________________________________<br>");out.println("Exception occurred: " + theException + "<br>");out.println("___________________________________________________<p><br>");theException. printStackTrace(out);

}catch(java.io.IOException e){

System.out.println("IOException occurred: " + e);}//endcatch

}//endcatch}

Chapter 12. WebSphere User Profile 225

Page 250: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The processLogin method (Figure 220) is called from the Login Page (Figure229 on page 231). Depending on whether the UserProfile with the UserNamealready exists or not, it calls the UserOutput page (Figure 231 on page 233)or UserCreate page (Figure 230 on page 232).

Figure 220. UserProfileCartServlet processLogin Method

The retrieveUserProfile method attempts to retrieve a UserProfile based onthe userName passed. If the UserProfile does not exist, it returns false,otherwise it returns true (Figure 221).

public void processLogin(HttpServletRequest request, HttpServletResponse response, UserCart userCart ,

Item itemInfo) throws java.lang.Exception{

boolean isFound = false;Item tempItem = null;javax.servlet.http.HttpSession session = request.getSession(true); isFound = retrieveUserProfile(userCart.getUserName());

if( isFound == true ) { // if the UserProfile already existsuserCart.setFirstName(profile.getFirstName());userCart.setLastName(profile.getLastName());userCart.setUserName(profile.getUserName());userCart.setLanguage(profile.getLanguage());session.putValue("userCart",userCart);tempItem = (Item)profile.retrieveShoppingCart();

if(tempItem != null) { //make sure there is an object in shopping cartitemInfo.setItem(tempItem.getItem());itemInfo.setPrice(tempItem.getPrice());

} //default output pagecallPage(getPageNameFromRequest(request), request, response);

}//endifelse { // UserCreate page is called if it's a new user

callPage("UserCreate", request, response); }//endelse

}

226 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 251: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 221. UserProfileCartServlet retrieveUserProfile Method

The userCreateToOutputPage method (Figure 222) is called from theUserCreate page (Figure 230 on page 232), it takes the parameters passed forthe UserProfile fields and then creates the UserProfile. It also stores the newinformation of the UserProfile inside an HttpSession object so it can beaccessed from other pages (see the itemCreateToOutputPage method inFigure 218 on page 224).

Figure 222. UserProfileCartServlet userCreateToOutputPage Method

public boolean retrieveUserProfile(String userName) {boolean isFound = true;

profile = UserProfile.retrieveUserProfileByUserName(userName);

if( profile == null) {isFound = false;

}

return isFound;}

public void userCreateToOutputPage( HttpServletRequest request,HttpServletResponse response, UserCart userCart) throws java.lang.Exception {

//create if it's not already createdjavax.servlet.http.HttpSession session = request.getSession(true);

userCart.setUserName(getParameter(request, "userName", true, true, true, null));

userCart.setFirstName(getParameter(request, "firstName", true, true, true, null));

userCart.setLastName(getParameter(request, "lastName", true, true, true, null));

userCart.setLanguage(getParameter(request, "language", true, true, true, null));

session.putValue("userCart",userCart);createUserProfile(userCart);

//default output pagecallPage(getPageNameFromRequest(request), request, response);

}

Chapter 12. WebSphere User Profile 227

Page 252: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Output ResultIn this section we will step through a flow of HTML pages to demonstrate thecreation or retrieval of a user profile starting from the login page.

The Login page (Figure 223) is the first page displayed. After entering theuser name, control passes to the next page, depending on whether a userprofile for the user name exists or not.

Figure 223. UserProfile Login Page

If the user name entered in the Login page does not exist in the UserProfiletable, the UserCreate page (Figure 224) is called. This page prompts you tocreate a new UserProfile.

Figure 224. UserProfile UserCreate Page

228 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 253: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Once the user profile is created, the result is displayed in the default outputpage (Figure 225).

Figure 225. UserProfile Default OutputPage After User Registration

You can create a new item to be added to the shopping cart part of theUserProfile. The shopping cart only takes one object. A new object alwaysoverwrites the old one. This is done using the ItemCreate page (Figure 226).

Figure 226. UserProfile ItemCreate Page

After submitting the item, the default output page with the newly createditem is displayed (Figure 227).

Chapter 12. WebSphere User Profile 229

Page 254: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 227. UserProfile Default Output Page After Item Creation

XML, HTML, and JSP FilesIn this section we list all the source files that control the servlet and theHTML output. The servlet knows from which page a request is initiated bylooking at the value of the hidden field PageName. This field is set in all JSPand HTML files.

XML Servlet Configuration FileThe UserProfileCartServlet.servlet file (Figure 228) is an XML file whichcontains the definition for all of the pages called by callPage method. Thepages listed in the servlet file are all of type JavaServer Pages.

230 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 255: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 228. UserProfileCartServlet.Servlet Control File

Login HTML FileThe UserProfileLogin.html file (Figure 229) is the first page displayed for theuser login.

Figure 229. UserProfileLogin.html File

<?xml version="1.0"?><servlet> <page-list> <default-page> <uri>/itso/jsp/UserProfileCartOutputPage.jsp</uri> </default-page> <error-page> <uri>/itso/jsp/UserProfileCartErrorPage.jsp</uri> </error-page> <page>

<uri>/itso/jsp/UserProfileCreate.jsp</uri><page-name>UserCreate</page-name>

</page> <page>

<uri>/itso/jsp/ItemInfoInputPage.jsp</uri><page-name>ItemCreate</page-name>

</page></page-list> <code>itso.wasdb.userprofile.UserProfileCartServlet</code> <description></description></servlet>

<HTML><HEAD> <TITLE>Login </TITLE> </HEAD> <BODY><FORM METHOD=POST

ACTION="/servlet/itso.wasdb.userprofile.UserProfileCartServlet">Please Input Your User Name:<INPUT TYPE=HIDDEN NAME="PageName" VALUE="Login"><TABLE BORDER=0 FRAME=NONE RULES=NONE ALIGN=LEFT WIDTH="50%"

CELLPADDING="4" CELLSPACING="1"><TR><TH ALIGN="LEFT" WIDTH="5%"></TH> <TH ALIGN="LEFT" WIDTH="45%"></TH>

</TR><TR><TD><INPUT TYPE=TEXT NAME="userName" ID="userName"> </TD> <TD><INPUT TYPE=SUBMIT NAME="submit" ID="submit" VALUE="Login"></TD></TR>

</TABLE><br CLEAR="LEFT"></FORM> </BODY></HTML>

Chapter 12. WebSphere User Profile 231

Page 256: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

JSP FilesThe UserProfileCreate.jsp file (Figure 230) contains the entry fields forcreating a new UserProfile.

Figure 230. UserProfileCreate.jsp File

<HTML><HEAD><TITLE>User Profile Create</TITLE></HEAD><BODY> <BEAN NAME="userProfileCart" TYPE="itso.wasdb.userprofile.UserCart" INTROSPECT=NO

CREATE=NO SCOPE=REQUEST></BEAN><form ACTION="/servlet/itso.wasdb.userprofile.UserProfileCartServlet" METHOD="POST"

ENCTYPE="application/x-www-form-urlencoded"><INPUT TYPE="HIDDEN" NAME="PageName" VALUE="UserCreate"><div align="center"><center><p><font SIZE="4">Register a New User</font></p> </center></div><div align="center"><center><table BORDER="0" WIDTH="85%"> <tr> <td WIDTH="100%">Enter the user parameters below and click Submit. A user profile

with the specified properties will be created if it does not already exist. Otherwise, you will receive a duplicate user message.</td>

</tr> <tr> <td WIDTH="100%"></td> </tr> </table> </center></div><div align="center"><center><table BORDER="0" CELLPADDING="4" CELLSPACING="1" WIDTH="50%" FRAME="NONE" RULES="NONE"> <tr>

<td><div align="right"><p>User Name: </td> <td><input TYPE="TEXT" NAME="userName" SIZE="25" ID="userName" VALUE=<INSERT BEAN="userProfileCart" PROPERTY="userName"></INSERT>></td> </tr> <tr> <td><div align="right"><p>First Name: </td> <td><input TYPE="TEXT" NAME="firstName" SIZE="25" ID="firstName"></td> </tr> <tr> <td><div align="right"><p>Last Name: </td> <td><input TYPE="TEXT" NAME="lastName" SIZE="25" ID="lastName"></td> </tr> <tr> <tr> <td><div align="right"><p>Language: </td> <td><input TYPE="TEXT" NAME="language" SIZE="25" ID="language"></td> </tr> <td></td> <td></td> </tr> <tr> <td COLSPAN="2"><div align="center"><center><p><input TYPE="SUBMIT"

NAME="submit" VALUE="Submit" ID="submit"> <input TYPE="RESET" NAME="reset" VALUE="Reset"

ID="reset"> </td> </tr> </table> </center></div></form></BODY></HTML>

232 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 257: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Notice the BEAN tag that refers to the UserCart JavaBean. The INSERT tagretrieves the userName property from the bean.

The UserProfileCartOutputPage.jsp File (Figure 231) displays the content ofthe UserProfile, including the contents of its shopping cart.

Figure 231. UserProfileCartOutputPage.jsp File

In this JSP file the userCart is defined in a BEAN tag and its property valuesare retrieved in INSERT tags.

The ItemInfoInputPage.jsp file (Figure 232) contains the entry fields forcreating a new Item.

<HTML><HEAD><TITLE>User Information</TITLE></HEAD><BODY><H2>User Information<br>

___________________________________________________</H2><BEAN NAME="userProfileCart" TYPE="itso.wasdb.userprofile.UserCart" INTROSPECT=NO

CREATE=NO SCOPE=REQUEST></BEAN><b> UserName :</b>

<INSERT BEAN="userProfileCart" PROPERTY="userName"> </INSERT><BR><b> FirstName:</b>

<INSERT BEAN="userProfileCart" PROPERTY="firstName"> </INSERT><BR><b> LastName :</b>

<INSERT BEAN="userProfileCart" PROPERTY="lastName"> </INSERT><BR><b> Language :</b>

<INSERT BEAN="userProfileCart" PROPERTY="language"> </INSERT><BR><H2><br>Item Detail<br>__________________________________________________</H2><BEAN NAME="itemInfo" TYPE="itso.wasdb.userprofile.Item" INTROSPECT=NO CREATE=NO SCOPE=REQUEST></BEAN>

<b> Item :</b> <INSERT BEAN="itemInfo" PROPERTY="item"></INSERT><BR><b> Price:</b> <INSERT BEAN="itemInfo" PROPERTY="price"></INSERT><BR>

<form ACTION="/servlet/itso.wasdb.userprofile.UserProfileCartServlet" METHOD="POST"ENCTYPE="application/x-www-form-urlencoded">

<input TYPE="HIDDEN" NAME="PageName" VALUE="UserOutput">

To overwrite the existing item or create a new one press:<input TYPE="SUBMIT" NAME="submit" VALUE="New Item" ID="submit">

</form></BODY></HTML>

Chapter 12. WebSphere User Profile 233

Page 258: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 232. ItemInfoInputPage.jsp File

The UserProfileCartErrorPage.jsp file (Figure 233) contains a message forthe error. The detail of the error is loaded into the page dynamically (Figure219 on page 225).

Figure 233. UserProfileCartErrorPage.jsp File

<HTML><HEAD><TITLE></TITLE></HEAD><BODY>

<FORM METHOD=POST ACTION="/servlet/itso.wasdb.userprofile.UserProfileCartServlet">Please complete the form and click on Submit.<input TYPE="HIDDEN" Name="PageName" VALUE="ItemCreate">

<TABLE BORDER=0 FRAME=NONE RULES=NONE ALIGN=LEFT WIDTH="50%" CELLPADDING="4" CELLSPACING="1">

<TR><TH ALIGN="LEFT" WIDTH="5%"></TH> <TH ALIGN="LEFT" WIDTH="45%"></TH></TR><TR> <TD>Item</TD> <TD><INPUT TYPE=TEXT NAME="item" ID="item"></TD></TR><TR> <TD>Price</TD> <TD><INPUT TYPE=TEXT NAME="price" ID="price"></TD></TR></TABLE><BR CLEAR="LEFT"><BR><INPUT TYPE=SUBMIT NAME="submit" ID="submit" VALUE="Submit"></FORM>

</BODY></HTML>

<HTML><HEAD><TITLE>User Profile Error</TITLE></HEAD><BODY><h3>An error has occurred using User Profile.</h3></BODY></HTML>

234 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 259: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Testing the User Profile Sample in VisualAge for JavaThe user profile sample will fail in the VisualAge for Java test environmentbecause no database information has been prepared for storing user profiles.

Setting up the DatabaseTo activate the user profile function we have to change a properties file of theWebSphere Test Environment:

c:\IBMVJava\ide\project_resources\IBM WebSphere Test Environment\properties\server\servlet\servletservice\userprofile.properties

Change the properties files as shown in Figure 234.

Figure 234. User Profiles Properties File

Source FilesThe source files must be placed into appropriate directories:

❑ UserProfileCartServlet.servlet: store in the project resources directory ofVisualAge for Java:

c:\IBMVJava\ide\project_resources\ITSO SG24 5471\itso\wasdb\userprofile

❑ UserProfileLogin.html: store in a subdirectory of the HTML directory:

c:\Program Files\IBM HTTP Server\htdocs\itso

❑ JSP Files: store in a subdirectory of the HTML directory:

c:\Program Files\IBM HTTP Server\htdocs\itso\jsp

# @(#)userprofile.properties ## User Profiles Configuration Screen#ncf.userprofile=truencf.userprofile.db.used=db2ncf.userprofile.db.jdbcdriver=COM.ibm.db2.jdbc.app.DB2Driverncf.userprofile.db.instance=ITSOWDBncf.userprofile.db.owner=ITSOncf.userprofile.tablename=userprofilencf.userprofile.userid=ITSOncf.userprofile.password=itsoncf.userprofile.classname=com.ibm.servlet.personalization.userprofile.UserProfile## Properties for connection manager initializationncf.userprofile.connmgr.poolname=JdbcDb2ncf.userprofile.connmgr.waitretry=false

Chapter 12. WebSphere User Profile 235

Page 260: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Run the User Profile SampleStart the WebSphere Test Environment and open a browser with the URL:

http://127.0.0.1:8080/itso/UserProfileLogin.html

The first access to a user profile creates the ITSO.USERPROFILE table inthe ITSOWDB database.

The output of the user profile sample should match the decription in “OutputResult” on page 228.

Running the User Profile Sample in WebSphereConfigure WebSphere as described in “Configuration” on page 214. Deploythe beans and the servlet to WebSphere:

c:\WebSphere\AppServer\servlets

The source files must be placed into appropriate directories:

❑ UserProfileCartServlet.servlet: store in the servlets directory ofWebSphere, together with the servlet code and the beans.

c:\WebSphere\AppServer\servlets\itso\wasdb\userprofile

❑ UserProfileLogin.html: store in a subdirectory of the HTML directory:

c:\Program Files\IBM HTTP Server\htdocs\itso

❑ JSP Files: store in a subdirectory of the HTML directory:

c:\Program Files\IBM HTTP Server\htdocs\itso\jsp

Open a browser with the URL:

http://hostname/itso/UserProfileLogin.html

The first access to a user profile creates the ITSO.USERPROFILE table inthe ITSOWDB database on the WebSphere server machine.

The output of the user profile sample should match the description in“Output Result” on page 228.

236 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 261: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

13 WebSphere Securityand the LDAPDirectoryIn this chapter we discuss securing access to resources using a directoryservice.

© Copyright IBM Corp. 1999 237

Page 262: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IntroductionA directory service is a combination of:

❑ An information repository: A database is often used to store locationinformation and other details about resources such as users, printers, fileservers, and application servers.

❑ An access method: The Lightweight Directory Access Protocol (LDAP)or other access methods can be used to communicate with directoryservice components.

❑ Related services: A directory service provides facilities for querying,manipulating, and authenticating the information in its database.

You might already have set up a directory service product to hold globalsecurity data that many other software applications, such as an applicationserver and your Web server, can use to authenticate users who try to accessresources.

WebSphere supports the use of three different directory service types:

❑ Domino 4.6

❑ Netscape Directory Server

❑ e-Network IBM Suite

The security access to the directory service is provided through ACL, accesscontrol list, in WebSphere. When using directory service for security,WebSphere acts as the client of the directory service. The setup for theresource security is done through an ACL. Resources such as servlets areassigned an ACL, and based on the permissions provided through the ACL,the level of access is provided.

Access Control ListsThe ACL associated with a resource specifies which users or groups in arealm are permitted to access the resource. ACLs, realms, and resources havethe following relationships (Figure 235):

❑ A realm can contain many ACLs. ❑ A realm can contain many resources. ❑ An ACL can belong to only one realm. ❑ A resource is associated with only one ACL. ❑ A resource can belong to only one realm. ❑ An ACL can be associated with many resources.

238 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 263: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 235. Relationships Between Realm, ACL, and Resource

In some cases, a service does not require its customers to be in an accesscontrol list. For example, many Web page (HTTP) services make theirdocuments available to all users without requiring them to register in anaccess control list (ACL).

RealmsA realm is a database of users, groups, and ACLs. A user must be defined in arealm in order to access any resources belonging to that realm.

A user can belong to several realms, but a user ID cannot be duplicatedwithin a realm. For example, the user amy can belong to the realmsfileRealm and anyRealm. Each of those realms can contain only one usernamed amy. The user amy can be given different permissions for differentresources in each realm.

A person, such as Amy, might have different user IDs in each realm. Forexample, she might be amy in the fileRealm, but is amy2 in the anyRealmbecause there is already a person in anyRealm using the user ID amy.

IBM WebSphere Application Server ships with some pre-established realms:

❑ The defaultRealm defines how users may access resources definedlocally. You can establish ACLs to determine which users and groups haveaccess to which resources.

❑ The NT realm and the UNIX realm define how users with accounts onyour operating systems may access WebSphere resources. Users definedin the operating system are shared by WebSphere and continue to existfor as long as they exist in the underlying system. The application servermanager interface lets you view this realm; to change it, you must use thefacilities provided by your operating system. Currently, WebSphere canshare users, but not groups, defined in the operating system.

Realm

ACL Resource

11

m

1 m

m

m = many

Chapter 13. WebSphere Security and the LDAP Directory 239

Page 264: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ The servletMgrRealm defines how servlets may access resourcesdefined remotely, such as remotely loaded servlets. The servlet ACL is theonly access control list in this realm. When a remotely loaded,digitally-signed servlet tries to access a protected resource, the digitalcertificate in the servlet is compared with digital certificates associatedwith users in the servletMgrRealm. The servletACL decides whetherpermission is granted or denied.

For example, suppose the digital certificate of userX is packaged in theanyServlet.JAR file. If userX is added to the servletMgrRealm, any servletcontaining the same digital certificate as that of userX (found inanyServlet.JAR) may execute and access resources granted to userX.

❑ Finally, the ldapRealm (Figure 240 on page 244) is displayed if you havea directory service enabled on the Directory Management page (Figure236 on page 241) of the WebSphere Application Server Administration.

Users and groups defined in the directory service are shared by WebSphereand continue to exist for as long as they exist in the directory service or untilyou disable directory management support. The application server managerinterface lets you view this realm; to change it, you must use the facilities theLDAP server provides.

For more information about LDAP, directory services, and the ldapRealm, seeUsing a directory service with Application Server in the WebSphere onlinedocumentation. Also refer to the LDAP Implementation Cookbook,SG24-5110.

ResourcesResources are the valuable items accessible by the Web server:

❑ HTML files and directories, such as http://www.anycompany.com ❑ Other files and directories, such as ftp://www.anycompany.com ❑ Web applications: Java servlets or CGI programs

and by the WebSphere Application Server:

❑ Java servlets ❑ Connections, sockets, files, and other resources used by servlets ❑ Custom servlets that enable access to enterprise resources and

applications (such as databases)

Each resource can be protected by establishing a single ACL for thatresource, in a single realm. The ACL specifies which users or groups areallowed to access or modify the resource.

240 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 265: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

For each resource to protect, you specify:

❑ An access control list (ACL)—a list defining who can use the resource ❑ A security realm—a logical security area the resource belongs to ❑ An authentication scheme—a way to verify users who ask for the resource

The relationship among these items will become apparent shortly.

Setup and ConfigurationYou must have installed a directory server and user IDs created for thedirectory server prior to starting the setup on WebSphere.

Netscape Directory Server 4.0 was used to provide security access to ourresources, namely servlets.

The following are the steps involved in setup and configuration of securitythrough directory service.

❑ Start the WebSphere Administration panel, see “WebSphereConfiguration” on page 6. Select Directory Management (Figure 236).

Figure 236. WebSphere Administration Setup for Directory Management

❑ From the WebSphere Administration main menu, select the AccessControl List and select the ldapRealm and click on the Add button (Figure237).

Chapter 13. WebSphere Security and the LDAP Directory 241

Page 266: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 237. WebSphere Access Control List Main Panel

❑ From the Add ACL panel, input the New ACL Name (Figure 238).

Figure 238. Adding a New Access Control List

❑ From the Access Control List main panel (Figure 237) select the newlycreated ACL and click on the lower Add button to add permissions to thenew ACL. Select the type of permissions you want to give to a user or agroup (Figure 239). As you may have noticed, the user IDs and group IDsare the same as the ones you have specified in the directory service.

242 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 267: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Note: To enable access to the servlets, you should Assign Permission for Filesand Folders. Files and Folders refers to local directories and files, includingservlets. Servlets refers to remotely loaded servlets. If you are unsure whichto choose, Files and Folders is the appropriate choice in most cases.

Figure 239. Add Permission to ACL

❑ At this point you have specified your ACL, and the ACL panel displaysinformation based on the choices you made in the Add Permission to ACLpanel (Figure 240).

Chapter 13. WebSphere Security and the LDAP Directory 243

Page 268: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 240. WebSphere Access Control List Main Panel with New ACL

❑ Next is to set up access to your resources based on the newly created ACL.Select Resources from the WebSphere Administration main menu. Fromthe Resources panel select the ldapRealm. Click on the Add button to adda resource to the desired ACL (Figure 241).

Figure 241. WebSphere Resources Security Setup

244 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 269: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

❑ From the Protect a Resource dialog, select a Scheme, ACL, and a Resourceto Protect, and click on the OK button (Figure 242).

Figure 242. Protect a Resource using Directory Service through ACL

After performing these steps you have specified your resource security accessbased on the setting in the directory service (Figure 243).

Figure 243. Resource Panel after Adding a Resource to be Protected

Chapter 13. WebSphere Security and the LDAP Directory 245

Page 270: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

246 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 271: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

14 Using SQLJ toAccess a DatabaseSQLJ is a method of accessing database information using embedded SQL inJava code. In this chapter we will discuss what you need in order to use SQLJand give a simple example of using SQLJ with WebSphere and DB2.

Note: To use the SQLJ functionality, you must install fixpack 8 for DB2Version 5.

© Copyright IBM Corp. 1999 247

Page 272: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

What is SQLJ?SQLJ allows Java programmers to create static SQL for Java applications aswell as the dynamic SQL which traditional JDBC drivers provide. The use ofstatic SQL allows all authority, syntax, access strategy, and logic checking tobe done at SQL compile time. This unique ability provides performanceincreases for applications that repeatedly use the same SQL.

SQLJ was developed as a combined effort by Oracle, Tandem, and IBM to addstatic SQL to JDBC. It has recently become an ANSI standard. Thespecification consists of three parts:

❑ Part 0 specifies the SQLJ language syntax and semantics for embeddedSQL statements in a Java application.

❑ Part 1 specifies extensions that define:

• Installation of Java classes in an SQL database• Invocation of static methods as stored procedures

❑ Part 2 specifies extensions for accessing Java classes as SQL distincttypes.

Most database vendors have implemented part 0 of this plan, but the goal isto gradually introduce the SQLJ technology into the products. We focus onlyon part 0 in this book.

SQLJ and VisualAge for JavaUnfortunately, VisualAge for Java 2.0 does not support SQLJ. SQLJoperability is scheduled for Version 3, which should be available in the thirdquarter of 1999.

VisualAge for Java Version 2 cannot be used with SQLJ because VisualAgedoes not recognize the precompiler directives that SQLJ uses before itstranslation. This implies that the embedded SQL statements and other SQLJresources will cause errors within VisualAge for Java.

This will cause some development slowdown, because you cannot use theWebSphere Test Environment and the VisualAge for Java debugger.

248 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 273: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SQLJ Translators, Input, and OutputTo compile Java code with embedded SQLJ, you must put your code througha translator that will comment out and preprocess the SQLJ code so that anormal Java compiler can successfully compile the code.

The naming convention for SQLJ states that all Java files with embeddedSQLJ should have an extension of .sqlj before they are translated. The SQLJtranslator is used to translate .sqlj files into .java files. It comments out all ofthe SQLJ code and replaces it with the proper Java code used to implementthe static SQL.

When this translation occurs, Java classes are created for the SQLJ iterators.Iterators are cursors that are used to store the results of the embedded SQLquery. Because the result sets can have different numbers of columns andcolumn types, a separate iterator must be created for each unique result set.You define a cursor to parse a result set using embedded SQL that is laterinterpreted by the translator.

A class and a serialized file are also created for the query profile. This profilemaintains the data used to keep the SQL static.

Updating Serialized ProfilesInstead of having to rebuild information as dynamic SQL does, the serializedprofile stores the information necessary to make the SQL execution performas quick as possible. The serialization file stores the bind information used toaccess the database.

This profile can be customized by running it through a customizer whichconnects to the database and updates the information stored regardingaccessing your data. This customizer is found in the same directory as thetranslator. For DB2 the customizer is called db2profc.exe. It has the followingusage:

db2profc -user=<user> -password=<password> url=<database url> <profile name>.ser

You should customize the profile when the tables significantly change involume. Failure to do so can cause inefficient access methods to be used toaccess the data. This is important, considering that performance is the mainpoint of using static SQL files.

Chapter 14. Using SQLJ to Access a Database 249

Page 274: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

DB2 Resources for SQLJFor applications written using SQLJ to work properly, certain resources mustbe available. It is imperative that you include the following files in your classpath. These files must be in the WebSphere class path as well.

c:\sqllib\java\db2java.zipc:\sqllib\java\runtime.zipc:\sqllib\java\sqlj.zip

The sqlj.zip file is included with the DB2 Software Developer’s Kit. It placesthe zip file in the same directory as other DB2 Java resources.

SQLJ is implemented using a JDBC connection to the database on WindowsNT. To execute the SQL, you must first create a connection and a connectioncontext as shown in our example.

Using the SQLJ Translator with DB2With the installation of DB2 Software Developer’s Kit, an executable namedsqlj.exe is placed into the d:\ sqllib\bin directory (where sqllib is the DB2installation directory). This file is the SQLJ translator.

The SQLJ command has the format:

sqlj <Java file name with SQLJ>

The output file of type .java can be used by any Java translator and can becompiled normally. The SQLJ translator, by default, automatically compilesthe output file and creates a serialized profile. The translator does not catcherrors in the Java source file, so make sure the file is syntactically correct.

Employees in Department ExampleWe use our example of finding all the employees in a specific department. Weimplement this example using a servlet and a bean. The servlet contains allthe Java code to communicate with the bean. The bean controls the retrievaland displaying of the data.

250 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 275: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

ServletThe SqljServ servlet (Figure 244) contains no SQLJ code, therefore it is notrun through the SQLJ translator. The servlet code invokes methods thatcontain SQLJ through the SQLJServBean.

Figure 244. SQLJ Example Servlet (SqljServ.java)

package itso.wasdb.sqlj;

import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class SqljServ extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res) {PrintWriter out = null;String drv = "COM.ibm.db2.jdbc.app.DB2Driver";String dep = "A00";SqljServBean sqljBean = new SqljServBean();

try { out = res.getWriter(); out.println("<HTML><BODY>");

Class.forName(drv).newInstance(); sqljBean.setUserID("itso"); sqljBean.setPassword("itso"); sqljBean.setURL("jdbc:db2:itsowdb"); sqljBean.startConnection(); sqljBean.executeSQLJ(out, dep);

}catch(SQLException sqlExcept) { sqlExcept.printStackTrace(out);catch (Exception except) {

if( out != null ) {out.println(except);except.printStackTrace(out);

}else {

System.out.println(except);except.printStackTrace();

}}

}}

Chapter 14. Using SQLJ to Access a Database 251

Page 276: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Bean with SQLJ Code Before TranslationThe SQLJServBean (Figure 245 and Figure 246) creates the connection,executes the SQL, and displays the result. These figures show the .sqlj codebefore translation.

Figure 245. SQLJ Example Servlet Bean (SqljServBean.sqlj) Part 1

package itso.wasdb.sqlj;

import java.io.*;import java.sql.*;import sqlj.runtime.*;import sqlj.runtime.ref.*;

#sql iterator DataCursor (String empno, String lastname, String workdept, String Sex);

public class SqljServBean {// Instance variable for the URL property

private String url=null;// Instance variable for the userID property

private String userID=null;// Instance variable for the password property

private String password=null;// Instance variable for Connection

private Connection con=null;

public void startConnection() throws SQLException{try {

con = DriverManager.getConnection(url, userID, password); con.setAutoCommit(false);DefaultContext ctx = new DefaultContext(con); DefaultContext.setDefaultContext(ctx);

} catch (SQLException e) {System.out.println("Error: could not get a default context");System.err.println(e) ;System.exit(1);

} catch (Exception e){System.out.println(e);

}return;}

}}

252 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 277: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The startconnection method creates a connection to the database and createsa default context. SQLJ uses the default context connection in use with itsserialized profile, so you must set one in your code.

Figure 246. SQLJ Example Servlet Bean (SqljServBean.sqlj) Part 2

public void executeSQLJ(PrintWriter out, String dep) throws SQLException {

DataCursor cursor1;

long count1 = 0;

// retrieve data from the databaseSystem.out.println("Retrieve some data from the database..."); #sql cursor1 = { SELECT empno, lastname, workdept, sex from itso.employee

where WORKDEPT = :dep }; // retrieve number of employees in the department #sql {SELECT count(*) into :count1 from employee where workdept = :dep };

try {outputInfo(cursor1, count1, out);

}catch (SQLException hmmm) { throw hmmm;}}

public void outputInfo(DataCursor cs, long count, PrintWriter out) throws SQLException{

out.println("<TABLE BORDER=3 FRAME=ALL CELLPADDING=1 CELLSPACING=1 COLS=4>");

out.println("<CAPTION ALIGN=TOP><b>UDB - " + count + " Employees in Department</b></CAPTION>");

out.println("<TR>");out.println("<TH ALIGN=CENTER WIDTH=20%>Emp Number ");out.println("<TH ALIGN=CENTER WIDTH=20%>Last Name ");out.println("<TH ALIGN=CENTER WIDTH=20%>Dept Name ");out.println("<TH ALIGN=CENTER WIDTH=20%>Sex ");

while(cs.next()) {out.print("<TR><TD ALIGN=CENTER>" + cs.empno());out.print("<TD ALIGN=CENTER>" + cs.lastname());out.print("<TD ALIGN=CENTER>" + cs.workdept());out.print("<TD ALIGN=CENTER>" + cs.Sex());

}out.println("</TABLE>");

}

Chapter 14. Using SQLJ to Access a Database 253

Page 278: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

The executeSQLJ method contains the embedded SQL. It creates a cursor tostore the result of the SQL query and returns the result set to the cursor.

The outputInfo method displays the information contained in the cursor. Ituses the PrintWriter class to write the results to the Web browser. You cansee how simple it is to retrieve a data item from the result set by the use ofthe cursor methods.

SQLJ Code After TranslationThe SQLJ code in these listings performs multiple functions. Each isdescribed here and the Java code resulting from translation is shown.

Iterator#sql iterator DataCursor (String empno, String lastname, String workdept,

String Sex)

This statement creates the iterator, or cursor, used to store the result set ofthe SQL query. Because the SQL can return varying columns and types, weneed to define an iterator before including what kind of output to expect so itcan properly store the information. The cursor data types and the data typesreturned from the SQL statement are compared and checked during thetranslation of the SQLJ code.

In Figure 247, we see the definition of the iterator. The SQLJ translatorcreates this code, which makes it extremely easy to manage the output ofqueries. You just call the method named after the column to retrieve theinformation stored in that column. The rows are traversed using theiterator’s next method as shown in the outputInfo method (Figure 246 onpage 253).

254 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 279: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 247. SQLJ Code after Translation: Iterator Class Definition

/*@lineinfo:generated-code*//*@lineinfo:10^1*/// ************************************************************// SQLJ iterator declaration:// ************************************************************

class DataCursor extends sqlj.runtime.ref.ResultSetIterImplimplements sqlj.runtime.NamedIterator{ public DataCursor(sqlj.runtime.profile.RTResultSet resultSet) throws java.sql.SQLException { super(resultSet); empnoNdx = findColumn("empno"); lastnameNdx = findColumn("lastname"); workdeptNdx = findColumn("workdept"); SexNdx = findColumn("Sex"); } public String empno() throws java.sql.SQLException {

return resultSet.getString(empnoNdx); }

private int empnoNdx; public String lastname() throws java.sql.SQLException {

return resultSet.getString(lastnameNdx); }

private int lastnameNdx; public String workdept() throws java.sql.SQLException {

return resultSet.getString(workdeptNdx); }

private int workdeptNdx; public String Sex() throws java.sql.SQLException {

return resultSet.getString(SexNdx); }

private int SexNdx;}// ************************************************************/*@lineinfo:user-code*//*@lineinfo:10^85*/

Chapter 14. Using SQLJ to Access a Database 255

Page 280: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Select Statement with Result Set#sql cursor1 = { SELECT empno, lastname, workdept, sex from itso.employee

where WORKDEPT = :dep };

This select statement is embedded SQL code that uses a host variable (:dep).You can see how simple it is to use the SQL and return the result into theiterator. Figure 248 shows the translated SQLJ code. It is challenging tounderstand this code, but notice the use of the connection context. This iswhy it is necessary to create a default connection context when you createyour initial connection to the database. Also notice how the code uses theProfileKeys. ProfileKeys are an index to all the profiles used in theapplication and are stored in the serialized files that allow SQLJ to be static.

Figure 248. SQLJ Code after Translation: Simple Select Statement

// ************************************************************// #sql cursor1 = { SELECT empno, lastname, workdept, sex from itso.employee

where WORKDEPT = :dep };// ************************************************************{ sqlj.runtime.ConnectionContext __sJT_connCtx =

sqlj.runtime.ref.DefaultContext.getDefaultContext(); if (__sJT_connCtx == null)

sqlj.runtime.error.RuntimeRefErrors.raise_NULL_CONN_CTX(); sqlj.runtime.ExecutionContext __sJT_execCtx = __sJT_connCtx.getExecutionContext(); if (__sJT_execCtx == null)

sqlj.runtime.error.RuntimeRefErrors.raise_NULL_EXEC_CTX(); String __sJT_1 = dep; sqlj.runtime.profile.RTStatement __sJT_stmt =

__sJT_execCtx.registerStatement(__sJT_connCtx, itso.wasdb.sqlj.SqljServBean_SJProfileKeys.getKey(0), 0);

try { __sJT_stmt.setString(1, __sJT_1); sqlj.runtime.profile.RTResultSet __sJT_result =

__sJT_execCtx.executeQuery(); cursor1 = new DataCursor(__sJT_result); } finally { __sJT_execCtx.releaseStatement(); }}// ************************************************************/*@lineinfo:user-code*//*@lineinfo:47^100*/

256 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 281: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Select Statement without Result Set#sql { SELECT count(*) into :count1 from employee where workdept = :dep };

This statement does not return a result set, so it does not require an iterator.Instead, this set simply counts the number of elements in the result andstores that number in a host variable (:count1). Figure 249 shows thetranslation of this statement.

Figure 249. SQLJ Code after Translation: Select Without Result Set

// ************************************************************// #sql { SELECT count(*) from employee where workdept = :dep };// ************************************************************{ sqlj.runtime.profile.RTResultSet __sJT_rtRs; sqlj.runtime.ConnectionContext __sJT_connCtx =

sqlj.runtime.ref.DefaultContext.getDefaultContext(); if (__sJT_connCtx == null)

sqlj.runtime.error.RuntimeRefErrors.raise_NULL_CONN_CTX(); sqlj.runtime.ExecutionContext __sJT_execCtx = __sJT_connCtx.getExecutionContext(); if (__sJT_execCtx == null)

sqlj.runtime.error.RuntimeRefErrors.raise_NULL_EXEC_CTX(); String __sJT_1 = dep; sqlj.runtime.profile.RTStatement __sJT_stmt =

__sJT_execCtx.registerStatement(__sJT_connCtx, itso.wasdb.sqlj.SqljServBean_SJProfileKeys.getKey(0), 1);

try { __sJT_stmt.setString(1, __sJT_1); sqlj.runtime.profile.RTResultSet __sJT_result = __sJT_execCtx.executeQuery(); __sJT_rtRs = __sJT_result; } finally { __sJT_execCtx.releaseStatement(); } try { sqlj.runtime.ref.ResultSetIterImpl.checkColumns(__sJT_rtRs, 1); if (!__sJT_rtRs.next()) { sqlj.runtime.error.RuntimeRefErrors.raise_NO_ROW_SELECT_INTO(); } count1 = __sJT_rtRs.getLongNoNull(1); if (__sJT_rtRs.next()) { sqlj.runtime.error.RuntimeRefErrors.raise_MULTI_ROW_SELECT_INTO(); } } finally { __sJT_rtRs.close(); }}// ************************************************************/*@lineinfo:user-code*//*@lineinfo:51^76*/

Chapter 14. Using SQLJ to Access a Database 257

Page 282: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Deployment of an SQLJ Servlet to WebSphereMoving the SQLJ servlet is relatively simple. Place the servlet files in thesame directory as the other servlets on your machine. It is important thatyou remember to move all of the class files that are output from thetranslator. Any iterators you had will create their own class file. A ProfileKeyclass, which is an index to your profiles, and the actually profile (.ser file) willalso be created and must be accessible by the servlet. The servlet directorycontaining your classes is a natural place to put both of these files.

You should also make sure that the proper class paths are listed in the JavaEngine setup (Figure 250). You must be sure to add the files:

c:\sqllib\java\db2java.zipc:\sqllib\java\runtime.zipc:\sqllib\java\sqlj.zip

Figure 250. WebSphere Application Server: Java Engine Setup

258 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 283: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

SQLJ Servlet OutputThe servlet is now ready to run under WebSphere. The output is shown inFigure 251.

Figure 251. Output of SQLJ Servlet Employees in Department Example

Chapter 14. Using SQLJ to Access a Database 259

Page 284: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

260 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 285: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Appendixes

© Copyright IBM Corp. 1999 261

Page 286: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

262 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 287: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

A Odds and EndsIn this chapter we describe the various odds and ends that we encounteredwhile working with the different database systems.

© Copyright IBM Corp. 1999 263

Page 288: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Different Mapping of SQL TypesAfter creating the database and inspecting it with the tools to build querystatements, we discovered that the databases differ in the way they interprettypes. To see this, it is sufficient to compare the mapping of the employeetable for DB2 (Figure 252), Oracle (Figure 253), and SQL Server (Figure 254).

As you can see, mapping differs in those fields related to dates and to theSMALLINT field. Unfortunately, this makes it impossible to use one metadata specification for the data access bean for all databases.

This applies to code that depends on the IBM data access beans, that is codegenerated by the Studio Wizards, code generated by the SmartGuides ofVisualAge for Java when using the Select bean, and also non-generated handwritten code.

Figure 252. Default Mapping for the Employee Table in DB2

264 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 289: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Figure 253. Default Mapping for the Employee Table in Oracle

Figure 254. Default Mapping for the Employee in ODBC/SqlServer

Appendix A. Odds and Ends 265

Page 290: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Correct Deployment of Enterprise BeansBecause the deployment of enterprise beans is a somewhat difficult step,especially because very few error messages are thrown that could indicatewhat was wrong, keep the following rules in mind:

❑ For a BMP bean, deploy the EJS file rather than the EJB file in VisualAgefor Java. This preserves the mapping to the database.

❑ In WebSphere, do not regenerate the bean, only redeploy it.

❑ Delete any unused containers (Entity and Session).

❑ Session containers must specify a valid DB2 database; also verify that thespecified user ID may access the database.

❑ To complete the deployment process, you have to stop WebSphere, thenstop the HTTP Server, and finally start the HTTP Server again, whichshould start up the WebSphere Servlet Service as well.

❑ Add memory to your computer; to use VisualAge for Java and WebSpherewe suggest 128MB minimum.

Data Access BeansIt seems that the data access beans do generally work better when the inputand output types are not specified using classes, but using integer values ofthe java.sql.Types class. Unfortunately, this creates problems with theWizards of WebSphere Studio, because they always generateClassName.class instead of Types.TYPE.

According to IBM support, this is a known bug and is fixed as of version 1.1 ofthe data access beans. Unfortunately this version is neither part ofWebSphere nor WebSphere Studio. Especially for WebSphere Studio, this isunfortunate because it makes the usage of Date fields impossible.

The bug manifests itself in the following example:

addColumn("HIREDATE", java.sql.Date.class, Types.DATE);addColumn("HIREDATE", Types.DATE, Types.DATE);

The first call fails and throws a com.ibm.db.DataException (Not supportedJava class is specified in parameter field), but the second call works.

The same problems appear with time stamps:

addColumn("HIREDATE", java.sql.Timestamp.class, Types.TIMESTAMP); <== failsaddColumn("HIREDATE", Types.TIMESTAMP, Types.TIMESTAMP); <== works

266 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 291: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

WebSphere StudioWhen WebSphere Studio 3 beta 2 is used to create a servlet accessing adatabase, there is a little bug when using the option Create page for when nodata is returned (Figure 255).

Figure 255. WebSphere Studio Database Wizard

If this option is used, the Database Wizard creates a servlet class thatcatches a com.ibm.webtools.runtime.NoDataException. This exception is partof the file webtlsrn.jar, which is part of the WebSphere Studio distribution,but apparently it is not part of WebSphere Application Server. The result isthat the servlet will not execute at all when published to the applicationserver because it cannot find the exception class.

One workaround is simply not to use this option, but this is not a solutionwhen one would like to use the servlets to update the database.

The second possibility is simply to copy the JAR file to the application server:

from: c:\WebSphere\StudioBeta\lib\AppServerV2\webtlsrn.jar to: c:\WebSphere\AppServer\lib

With this solution, the generated servlet works well.

Appendix A. Odds and Ends 267

Page 292: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

268 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 293: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

B Special NoticesThis publication is intended to help Java developers develop enterpriseapplications with VisualAge for Java Enterprise Version 2 and IBMWebSphere, together with relational database systems. The information inthis publication is not intended as the specification of any programminginterfaces that are provided by VisualAge for Java Enterprise and IBMWebSphere. See the PUBLICATIONS section of the IBM ProgrammingAnnouncement for VisualAge for Java Enterprise and IBM WebSphere formore information about what publications are considered to be productdocumentation.

References in this publication to IBM products, programs or services do notimply that IBM intends to make these available in all countries in whichIBM operates. Any reference to an IBM product, program, or service is notintended to state or imply that only IBM's product, program, or service maybe used. Any functionally equivalent program that does not infringe any ofIBM's intellectual property rights may be used instead of the IBM product,program or service.

Information in this book was developed in conjunction with use of theequipment specified, and is limited in application to those specific hardwareand software products and levels.

© Copyright IBM Corp. 1999 269

Page 294: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM may have patents or pending patent applications covering subjectmatter in this document. The furnishing of this document does not give youany license to these patents. You can send license inquiries, in writing, to theIBM Director of Licensing, IBM Corporation, North Castle Drive, Armonk,NY 10504-1785.

Licensees of this program who wish to have information about it for thepurpose of enabling: (i) the exchange of information between independentlycreated programs and other programs (including this one) and (ii) the mutualuse of the information which has been exchanged, should contact IBMCorporation, Dept. 600A, Mail Drop 1329, Somers, NY 10589 USA.

Such information may be available, subject to appropriate terms andconditions, including in some cases, payment of a fee.

The information contained in this document has not been submitted to anyformal IBM test and is distributed AS IS. The information about non-IBM("vendor") products in this manual has been supplied by the vendor and IBMassumes no responsibility for its accuracy or completeness. The use of thisinformation or the implementation of any of these techniques is a customerresponsibility and depends on the customer's ability to evaluate andintegrate them into the customer's operational environment. While each itemmay have been reviewed by IBM for accuracy in a specific situation, there isno guarantee that the same or similar results will be obtained elsewhere.Customers attempting to adapt these techniques to their own environmentsdo so at their own risk.

Any pointers in this publication to external Web sites are provided forconvenience only and do not in any manner serve as an endorsement of theseWeb sites.

Any performance data contained in this document was determined in acontrolled environment, and therefore, the results that may be obtained inother operating environments may vary significantly. Users of this documentshould verify the applicable data for their specific environment.

This document contains examples of data and reports used in daily businessoperations. To illustrate them as completely as possible, the examplescontain the names of individuals, companies, brands, and products. All ofthese names are fictitious and any similarity to the names and addressesused by an actual business enterprise is entirely coincidental.

Reference to PTF numbers that have not been released through the normaldistribution process does not imply general availability. The purpose ofincluding these reference numbers is to alert IBM customers to specificinformation relative to the implementation of the PTF when it becomes

270 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 295: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

available to each customer according to the normal IBM PTF distributionprocess.

The following terms are trademarks of the International Business MachinesCorporation in the United States and/or other countries:

The following terms are trademarks of other companies:

C-bus is a trademark of Corollary, Inc. in the United States and/or othercountries.

Java and all Java-based trademarks and logos are trademarks or registeredtrademarks of Sun Microsystems, Inc. in the United States and/or othercountries.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks ofMicrosoft Corporation in the United States and/or other countries.

PC Direct is a trademark of Ziff Communications Company in the UnitedStates and/or other countries and is used by IBM Corporation under license.

ActionMedia, LANDesk, MMX, Pentium and ProShare are trademarks ofIntel Corporation in the United States and/or other countries.

UNIX is a registered trademark in the United States and/or other countrieslicensed exclusively through X/Open Company Limited.

SET and the SET Logo are trademarks owned by SET Secure ElectronicTransactions LLC.

Other company, product, and service names may be trademarks or servicemarks of others.

IBM AS/400 DB2CICS OS/2OS/390 OS/400S/390 TeamConnectionThinkPad VisualAgeWebSphere

Appendix B. Special Notices 271

Page 296: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

272 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 297: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

C Related PublicationsThe publications listed in this section are considered particularly suitable fora more detailed discussion of the topics covered in this redbook.

© Copyright IBM Corp. 1999 273

Page 298: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

International Technical Support OrganizationPublications

For information on ordering these ITSO publications see “How to Get ITSORedbooks” on page 277.

❑ Developing an e-Business Application for the WebSphere ApplicationServer, SG24-5423

❑ VisualAge for Java Enterprise Version 2: Persistence Builder with GUIs,Servlets, and Java Server Pages, SG24-5426

❑ WebSphere Application Servers - Standard and Advanced, SG24-5460

❑ Enterprise JavaBeans Development Using VisualAge for Java, SG24-5429

❑ Java Application Development for CICS: Base Services and CORBA ClientSupport, SG24-5275

❑ Using VisualAge Smalltalk ObjectExtender, SG24-5258

❑ VisualAge for Java Enterprise Version 2: Data Access Beans - Servlets -CICS Connector, SG24-5265

❑ Programming with VisualAge for Java Version 2, SG24-5264, published byPrentice Hall, ISBN 0-13-021298-9, 1999 (IBM form number SR23-9016)

❑ VisualAge for Java Enterprise Version 2 Team Support, SG24-5245

❑ Using VisualAge for Java Enterprise Version 2 to Develop CORBA andEJB Applications, SG24-5276

❑ VisualAge Java-RMI-Smalltalk, The ATM Sample from A to Z, SG24-5418

❑ Using VisualAge UML Designer, SG24-4997

❑ Application Development with VisualAge for Java Enterprise, SG24-5081

❑ Creating Java Applications with NetRexx, SG24-2216

❑ Unlimited Enterprise Access with Java and VisualAge Generator,SG24-5246

❑ From Client/Server to Network Computing, A Migration to Java,SG24-2247

❑ Connecting the Enterprise to the Internet with MQSeries and VisualAge forJava, SG24-2144

274 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 299: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Redbooks on CD-ROMsRedbooks are also available on the following CD-ROMs. Click the CD-ROMsbutton at http://www.redbooks.ibm.com/ for information about all the CD-ROMsoffered, updates and formats.

Other PublicationsThese publications are also relevant as further information sources:

❑ Developing JavaBeans with VisualAge for Java Version 2, SC34-4735

❑ Design Patterns: Elements of Reusable Object-Oriented Software, ErichGamma, Richard Helm, Ralph Johnson, and John Vlissides, published byAddison-Wesley Professional Computing Series, ISBN 0-201-63361, 1995(IBM form number SR28-5629)

CD-ROM Title Collection KitNumber

System/390 Redbooks Collection SK2T-2177Networking and Systems Management Redbooks Collection SK2T-6022Transaction Processing and Data Management Redbooks Collection SK2T-8038Lotus Redbooks Collection SK2T-8039Tivoli Redbooks Collection SK2T-8044AS/400 Redbooks Collection SK2T-2849Netfinity Hardware and Software Redbooks Collection SK2T-8046RS/6000 Redbooks Collection (BkMgr) SK2T-8040RS/6000 Redbooks Collection (PDF Format) SK2T-8043Application Development Redbooks Collection SK2T-8037IBM Enterprise Storage and Systems Management Solutions SK3T-3694

Appendix C. Related Publications 275

Page 300: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

276 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 301: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

How to Get ITSO Redbooks

This section explains how both customers and IBM employees can find out about ITSOredbooks, redpieces, and CD-ROMs. A form for ordering books and CD-ROMs by fax ore-mail is also provided.

• Redbooks Web Site http://www.redbooks.ibm.com/

Search for, view, download or order hardcopy/CD-ROM redbooks from the redbooks website. Also read redpieces and download additional materials (code samples ordiskette/CD-ROM images) from this redbooks site.

Redpieces are redbooks in progress; not all redbooks become redpieces and sometimes justa few chapters will be published this way. The intent is to get the information out muchquicker than the formal publishing process allows.

• E-mail Orders

Send orders by e-mail including information from the redbooks fax order form to:

• Telephone Orders

• Fax Orders

This information was current at the time of publication, but is continually subject to change.The latest information may be found at the redbooks Web site.

In United StatesOutside North America

e-mail [email protected] information is in the “How to Order” section at thissite:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)Canada (toll free)Outside North America

1-800-879-27551-800-IBM-4YOUCountry coordinator phone number is in the “How to Order”section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)CanadaOutside North America

1-800-445-92691-403-267-4455Fax phone number is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

IBM employees may register for information on workshops, residencies, and redbooks byaccessing the IBM Intranet Web site at http://w3.itso.ibm.com/ and clicking the ITSOMailing List button. Look in the Materials repository for workshops, presentations,papers, and Web pages developed and written by the ITSO technical professionals; clickthe Additional Materials button. Employees may access MyNews at http://w3.ibm.com/ forredbook. residency, and workshop announcements.

IBM Intranet for Employees

© Copyright IBM Corp. 1999 277

Page 302: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

IBM Redbook Fax Order Form

Please send me the following:

We accept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card notavailable in all countries. Signature mandatory for credit card payment.

Title Order Number Quantity

First name Last name

Company

Address

City Postal code

Telephone number Telefax number VAT number

Invoice to customer number

Country

Credit card number

Credit card expiration date SignatureCard issued to

278 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 303: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

List of Abbreviations

API application programming interface

ASP Active Server Pages

ATM automated teller machine

AWT Abstract Windowing Toolkit

CGI Common Gateway Interface

CORBA Common Object Request BrokerArchitecture

DBMS database management system

DLL dynamic link library

GUI graphical user interface

HTML Hypertext Markup Language

HTTP Hypertext Transfer Protocol

IBM International Business MachinesCorporation

IDE integrated developmentenvironment

ITSO International Technical SupportOrganization

JAR Java archive

JDBC Java Database Connectivity

JDK Java Developer’s Kit

JFC Java Foundation Classes

JSDK Java Servlet Development Kit

JSP Java Server Pages

JVM Java Virtual Machine

ODBC Open Database Connectivity

PIN personal identification number

RDBMS relational database managementsystem

RMI Remote Method Invocation

SQL structured query language

TCP/IP Transmission ControlProtocol/Internet Protocol

© Copyright IBM Corp. 1999

UOW unit of work

URL uniform resource locator

WWW World Wide Web

279

Page 304: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

280 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 305: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Index

Aaccess control list 238alias 4Apache 4, 5Application Server

see WebSphereassembly stages 196

Bbean managed persistence 132, 164

Cclass path 129

Java 60Persistence Builder 130VisualAge for Java 48WebSphere 49, 129WebSphere Studio 181

configurationsecurity 241VisualAge for Java 10WebSphere 6WebSphere Studio 181

publishing 194connection

data access beans 89JDBC 83, 112

connection manager 65, 84JDBC 69sample 70

data access beans 98DB2 77Oracle 79SQL Server 79

servlet interaction 66connection pool 67, 68, 84container managed persistence 132, 133

Ddata access beans 81

EJB persistence 167output tailoring 96

© Copyright IBM Corp. 1999

sampleconnection manager 98DB2 86Oracle 95SQL Server 95

servlet sample 86SQL types 266

Database Wizard 188, 200datastore

activation 126DB2

application driver 44Client Application Enabler 44Command Window 24Control Center 22create database 23data load 26fixpack 22, 247installation 22JDBC 44, 82

applet server 45drivers 26

network driver 45, 56sample

connection manager 77data access beans 86EJB 170JDBC 56Persistence Builder 112, 127SQLJ 251WebSphere Studio 183

Software Developer’s Kit 250SQL types 264SQLJ 22, 249table creation 24

DBNavigator bean 82debugging

VisualAge for Java 210directory service 238, 245document root 4

EEJB

container 132, 133, 166Development Environment

VisualAge for Java 134fields 138

281

Page 306: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

generate code 143group 134mapping 142methods 139primary key 137sample

DB2 133servlet 174

server 132, 133, 143, 144test client 145

enterprise beanapplication sample 160deployment 149, 177, 266servlet sample 153test 143test client 145

Enterprise Java Server 132Enterprise JavaBeans

architecture 131see also enterprise beans

Enterprise Update 10entity bean 132

Hhome interface 132, 146HTML

visual composition 122HTTP Server 3, 152, 195

installation 4

Iimport

schema 112installation

DB2 UDB 22HTTP Server 4Oracle 27SQL Server 33VisualAge for Java 10WebSphere 5WebSphere Studio 181

Internet Explorer 3iterator 254ITSO

project 17user ID 23

itso.wasdb.accessbean package 86itso.wasdb.connaccess package 98

itso.wasdb.connmgr package 70itso.wasdb.ejb package 134itso.wasdb.ejb.client package 160itso.wasdb.jdbc package 53itso.wasdb.persist package 118itso.wasdb.persist.gui package 121itso.wasdb.persist.metadata package 121itso.wasdb.persist.Services package 120itso.wasdb.studio package 191

JJava Database Connectivity

see JDBCJava Foundation Classes

see SwingJavaServer Pages

see JSPJDBC

applet server 56connection 83, 112

manager 69DB2 26, 44drivers 43ODBC bridge 38, 47, 82Oracle 27, 32, 46programming examples 53result set 85sample

DB2 56Oracle 57run 60SQL Server 58test 60

servlet 61simple application 53SQL classes 82SQL Server 38, 47SQLJ 248statement types 85URL 150VisualAge for Java 10, 48WebSphere 7, 49

JSP 12, 180, 187, 193servlet invocation 202

JSP Page Compile Generated Code 12JTable 82

282 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 307: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

LLDAP 238, 240Lotus Domino Go Webserver 5

MMap Browser 111, 116, 142Model Browser 111, 115

NNetObjects

BeanBuilder 180Fusion 180ScriptBuilder 180

NetscapeDirectory Server 238Enterprise Server 5Navigator 3

OODBC 82

data source 38, 47, 58Oracle

create tables 29data load 31installation 27JDBC 27, 32, 46OCI driver 46Persistence Builder 111sample

connection manager 79data access beans 95EJB 170JDBC 57Persistence Builder 127WebSphere Studio 184

SQL types 264thin client driver 46user ID 27

PPage Designer 202persistence 110Persistence Builder 109

EJB mapping 140palette 123result table 125sample 112

DB2 127Oracle 127servlet 121SQL Server 127

tools 110primary key 137project view 192, 212

QQuick Start 10, 82

Rrealm 238, 239relational database

products 21remote interface 133repository 17resource 240result set

JDBC 85SQLJ 256

Rollup 2 10

Ssample

code 15database 21

Schema Browser 111, 112, 140schema import 112Secure Socket Layer 4security 237Select bean 81, 82, 88select statement

data access beans 91SQLJ 256

serialization 110SQLJ 249

SERunner 12, 97, 106, 158class path 12

service classes 119servlet

configuration file 208, 210configurationl file 11data access beans 86deployment 107, 128directory 11EJB sample 153, 174

283

Page 308: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

JDBC sample 61launcher 63, 106location 7Persistence Builder sample 121run

VisualAge for Java 12, 63, 97WebSphere 63

security 243SQLJ sample 251test 197URL 7visual composition 86WebSphere Studio sample 188

Servlet Builder 86, 122session bean 132SmartGuide

EJB 136Persistence Builder code generation 118SQL Assist 81, 91

SQLtypes 171, 264

SQL Assist SmartGuide 81, 91SQL Server

create database 33create tables 34data load 35installation 33JDBC 38, 47Persistence Builder 111sample

connection manager 79data access beans 95EJB 170JDBC 58Persistence Builder 127WebSphere Studio 184

SQL types 264user ID 34

SQL Wizard 183, 198SQLJ 22, 247

deployment 258iterator 254select 256translator 249, 250

Swing 82

Ttest client 145, 152, 174

UUDB

see DB2

VVisualAge for Java 9

class path 48enterprise bean test 143export 159installation 10JDBC 10, 48

test 60persistence builder 109Professional Edition 180Servlet Builder 86servlet debugging 210setup for EJB 134SQLJ 248

WWebSphere 3, 5

administration 6, 7, 67, 129class path 129EJB deployment 149, 177installation 5Java engine 129JDBC 7, 49servlet

deployment 107, 128service 8, 152

SQLJ deployment 258start/stop 8Studio 179Test Environment 10, 63, 158

class path 13WebSphere Studio

Page Designer 202publish 194sample

DB2 183Oracle 184servlet 188SQL Server 184

XXML

servlet configuration file 11, 193, 210

284 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server

Page 309: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

© Copyright IBM Corp. 1999 285

ITSO Redbook Evaluation

IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL ServerSG24-5471-00

Your feedback is very important to help us maintain the quality of ITSO redbooks. Please completethis questionnaire and return it using one of the following methods:

• Use the online evaluation form found at http://www.redbooks.ibm.com/• Fax this form to: USA International Access Code + 1 914 432 8264• Send your comments in an Internet note to [email protected]

Which of the following best describes you?_ Customer _ Business Partner _ Solution Developer _ IBM employee_ None of the above

Please rate your overall satisfaction with this book using the scale:(1 = very good, 2 = good, 3 = average, 4 = poor, 5 = very poor)

Overall Satisfaction __________

Please answer the following questions:

Was this redbook published in time for your needs? Yes___ No___

If no, please explain:

What other redbooks would you like to see published?

Comments/Suggestions: (THANK YOU FOR YOUR FEEDBACK!)

Page 310: Manual - Programacion - Java - Ibm Websphere and Visualage for Java Database Integration With Db2 o

Printed in the U.S.A.

SG24-5471-00

IBM

WebSp

herean

dV

isualAge

forJava

Database

Integration

with

DB

2,Oracle,an

dSQ

LServer

SG

24-5471-00