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 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server September 1999 SG24-5471-00 International Technical Support Organization Copyright International Business Machines Corporation 1999. All rights reserved. Note to U.S Government Users Documentation related to restricted rights Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp. First Edition (September 1999) Thi s edi ti on appl i es to I BM WebSpher e Appl i cati on Ser ver Ver si on 2.0.2 I BM WebSpher e Studi o Ver si on 3.0 beta 2 Vi sual Age for Java Ver si on 2 wi th Rol l up 2 and Enter pr i se Update DB2 Uni ver sal Database Ver si on 5.2 Or acl e Ver si on 8 Mi cr osoft SQL Ser ver Ver si on 7 for use wi th the Wi ndows NT Operati ng System, Servi ce Pack 4. SampleCodeon theInternet: Comments may be addr essed to: I BM Corpor ati on, I nter nati onal Techni cal Support Organi zati on Dept. QXXE Bui l di ng 80-E2 650 Harr y Road San Jose, Cal i forni a 95120-6099 When you send i nfor mati on to I BM, you grant I BM a non-excl usi ve ri ght to use or di str i bute the i nformati on i n any way i t bel i eves appropr i ate wi thout i ncur r i ng any obl i gati on to you. The sampl e code for thi s redbook i s avai l abl e as 5471samp.zi p fi l e on the I TSO home page on the I nter net: ftp://www.redbooks.ibm.com/redbooks/SG245471/ Downl oad the sampl e code and r ead Chapter 3, I TSO Sampl e Appl i cati ons on page 15. Before usi ng thi s i nformati on and the pr oduct i t supports, be sure to read the gener al i nfor mati on i n Appendi x B, Speci al Noti ces on page 269. TakeNote! Copyright IBM Corp. 1999 iii Contents Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i x Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi i Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi x The Team That Wrote Thi s Redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx Comments Wel come . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi Part 1. Introduction to IBM WebSphere and VisualAge for J ava .1 Chapter 1. HTTP Server and WebSphere Application Server. . . . 3 Envi ronment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 I BM HTTP Ser ver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Confi gur ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 I BM WebSphere Appl i cati on Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 WebSphere I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 WebSphere Confi gurati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 WebSphere Confi gurati on for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Starti ng and Stoppi ng WebSpher e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Chapter 2. VisualAge for J ava Enterprise Version 2 . . . . . . . . . . . . 9 Vi sual Age for Java I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Vi sual Age for Java Confi gur ati on for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . 10 Vi sual Age for Java Confi gur ati on for WebSphere . . . . . . . . . . . . . . . . . . . . 10 WebSpher e i n Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Defaul t Di r ector i es for Ser vl ets and JSP fi l es . . . . . . . . . . . . . . . . . . . . 11 Compi l ed JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Runni ng Ser vl ets i n Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . . . 12 Chapter 3. I TSO Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . 15 Sampl e Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Reposi tor y Export Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 iv IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Part 2. Database Setup and J DBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 Chapter 4. Relational Database Installation and Setup. . . . . . . . 21 DB2 UDB I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 DB2 UDB Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 DB2 UDB Tabl e Cr eati on. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Loadi ng the Tabl e Data I nto DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 DB2 JDBC Dr i ver s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Or acl e 8 I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Oracl e Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Oracl e Tabl e Cr eati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 I mpor ti ng the Tabl e Data i nto Oracl e . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Oracl e JDBC Dr i vers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 SQL Server I nstal l ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 SQL Ser ver Database Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 SQL Ser ver Tabl e Creati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 I mpor ti ng the Tabl e Data i nto SQL Server. . . . . . . . . . . . . . . . . . . . . . . 35 SQL Ser ver JDBC Dri vers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 ODBC Data Source Setup for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Chapter 5. J ava Database Connectivity. . . . . . . . . . . . . . . . . . . . . . . 43 DB2 UDB JDBC Dri ver s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 DB2 Appl i cati on Dri ver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 DB2 Network Dri ver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Or acl e JDBC Dri ver s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Oracl e Thi n Cl i ent Dri ver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Oracl e OCI Dri ver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 SQL Server JDBC Dr i ver s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Confi guri ng Vi sual Age for Java for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Confi guri ng WebSpher e for JDBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Part 3. Database ProgrammingExamples . . . . . . . . . . . . . . . . . . . . .51 Chapter 6. J DBC Programming Examples . . . . . . . . . . . . . . . . . . . . 53 Si mpl e JDBC Appl i cati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 DB2 Uni versal Database JDBC Code Exampl e . . . . . . . . . . . . . . . . . . . . . . 56 Or acl e JDBC Code Exampl e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 SQL Server JDBC Code Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Runni ng Appl i cati ons wi th JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Testi ng the JDBC Appl i cati ons i n Vi sual Age for Java. . . . . . . . . . . . . . 60 Runni ng the JDBC Appl i cati ons i n the Oper ati ng System . . . . . . . . . . 60 Si mpl e JDBC Servl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 v Testi ng the Ser vl et i n Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . 63 Runni ng the Ser vl et i n WebSpher e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Chapter 7. I BM Connection Manager . . . . . . . . . . . . . . . . . . . . . . . . . 65 Confi gurati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Connecti on Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 I BM Connecti on Manager and Pure JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . 69 I BM Connecti on Manager Exampl es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Usi ng the I BM Connecti on Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 HTML Fi l e for Accessi ng the Servl ets . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Runni ng the Exampl e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 DbaseConnMgr Cl ass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Oracl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Mi cr osoft SQL Ser ver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Chapter 8. Data Access Beans: VisualAge for J ava . . . . . . . . . . . . 81 Loadi ng the Data Access Bean Feature. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Data Access Beans and the Standard SQL Cl asses . . . . . . . . . . . . . . . . . . . 82 DatabaseConnecti on and java.sql .Connecti on . . . . . . . . . . . . . . . . . . . . 83 Statement Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Resul tSet Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Bui l di ng a Servl et usi ng Data Access Beans. . . . . . . . . . . . . . . . . . . . . . . . . 86 Sampl e Data Access Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Cr eati ng a Ser vl et Vi sual l y usi ng Data Access Beans . . . . . . . . . . . . . . 86 Usi ng the Connecti on Manager and Data Access Beans . . . . . . . . . . . . . . . 98 Cl ass Defi ni ti on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 I ni ti al i zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Form Parameter Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Form Processi ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Empl oyee Retri eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Empl oyee Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Testi ng the Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Depl oyi ng Servl ets to WebSpher e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Chapter 9. Persistence Builder: VisualAge for J ava . . . . . . . . . . 109 What i s Persi stence?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Usi ng Databases to Pr ovi de Persi stence . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Per si stence Bui l der Tool s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Vendor Speci fi c Consi derati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Per si stence Bui l der Exampl e: Empl oyees i n Depar tment . . . . . . . . . . . . . 112 I mpor t the Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Generate and Val i date the Object Model . . . . . . . . . . . . . . . . . . . . . . . 115 I nspect the Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 vi IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Generate the Java Code for the Object Model . . . . . . . . . . . . . . . . . . . 118 Generate the Java Code for the Servi ce Cl asses. . . . . . . . . . . . . . . . . . 119 Bui l d the Servl et. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Changi ng the Datastor e Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Depl oyi ng a Servl et to WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Chapter 10. Enterprise J avaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Enter pri se JavaBeans fr om a Bi rds-Eye Per specti ve . . . . . . . . . . . . . . . . 132 A Cl oser Look . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Devel opi ng a Contai ner Managed Persi stence Enti ty Bean . . . . . . . . . . . 133 Setup of Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Cr eate a Department Enterpr i se Bean . . . . . . . . . . . . . . . . . . . . . . . . . 135 Add the Properti es and Methods to the Bean . . . . . . . . . . . . . . . . . . . . 137 Map the Bean to the Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 Generate the Code and Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Depl oy the Enter pri se Bean to WebSphere . . . . . . . . . . . . . . . . . . . . . . . . . 149 Access the Depar tment Bean from a Servl et. . . . . . . . . . . . . . . . . . . . . . . . 153 Cl ass Decl arati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Perfor m Task Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 I ni ti al i zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Retr i eve a Department Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Cr eate or Fi nd a Depar tment Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Update the Depar tment Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Test the Ser vl et i n Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . . . 158 Test the Ser vl et i n WebSpher e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Access the Depar tment Bean from an Appl i cati on . . . . . . . . . . . . . . . . . . . 160 Cr eate the GUI Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Cr eate the Connecti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Test the Appl et or Appl i cati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Devel opi ng a Bean Managed Persi stence Enti ty Bean. . . . . . . . . . . . . . . . 164 Cr eate an Empl oyee Enterpr i se Bean wi th the SmartGui de. . . . . . . . 164 Add Properti es and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Pr ovi de the Empl oyee Bean wi th Per si stence Functi onal i ty . . . . . . . . 166 The Empl oyeeStor age Cl ass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Testi ng the Empl oyee Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Access the Empl oyee Bean from a Servl et . . . . . . . . . . . . . . . . . . . . . . 174 Depl oyment of the Empl oyee Bean to WebSphere . . . . . . . . . . . . . . . . 177 Chapter 11. WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 WebSpher e Studi o Tool s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 I nstal l ati on and Confi gurati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Project Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Create an SQL Statement and Servl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 vii Create the Ser vl et and JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Pr oject Vi ew after the Database Wi zar d . . . . . . . . . . . . . . . . . . . . . . . . 192 Publ i sh the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Publ i shi ng Confi gur ati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Assembl y Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Publ i shi ng Tar gets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Testi ng the Generated Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Enhanced I nsert Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Cr eate an SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Cr eate a Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Vi ewi ng the Resul t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Determi ne al l Avai l abl e Department Number s . . . . . . . . . . . . . . . . . . 201 I nvoke the Ser vl et from a JSP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Save the Modi fi ed HTML Page as a JSP. . . . . . . . . . . . . . . . . . . . . . . . 207 Modi fy the Generated Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Test the JSP and the Servl et i n WebSphere . . . . . . . . . . . . . . . . . . . . . 208 Debuggi ng the Servl ets i n Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . 210 Hi nts and Ti ps for WebSphere Studi o. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Synchr oni zati on between Devel opment and Publ i shi ng Vi ew. . . . . . . 211 Checkout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Publ i shi ng War ni ngs About Ol d Cl ass Fi l es . . . . . . . . . . . . . . . . . . . . . 211 Mi smatch between Ser vl et and Servl et Confi gurati on. . . . . . . . . . . . . 211 Project Vi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 Chapter 12. WebSphere User Profile. . . . . . . . . . . . . . . . . . . . . . . . . 213 Descri pti on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Confi gurati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Enabl e Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Database Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Connecti on Manager Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 User Profi l e Create, Update and Retri eve. . . . . . . . . . . . . . . . . . . . . . . . . . 218 Cr eate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Retr i eve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 UserPr ofi l e Exampl e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Cl asses and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Output Resul t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 XML, HTML, and JSP Fi l es. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 Testi ng the User Profi l e Sampl e i n Vi sual Age for Java . . . . . . . . . . . . 235 Runni ng the User Pr ofi l e Sampl e i n WebSpher e . . . . . . . . . . . . . . . . . 236 Chapter 13. WebSphere Security and the LDAP Directory . . . . 237 I ntr oducti on. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 viii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Access Control Li sts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Real ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 Setup and Confi gur ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 Chapter 14. Using SQLJ to Access a Database. . . . . . . . . . . . . . . . 247 What i s SQLJ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 SQLJ and Vi sual Age for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 SQLJ Transl ator s, I nput, and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Updati ng Ser i al i zed Profi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 DB2 Resour ces for SQLJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Usi ng the SQLJ Tr ansl ator wi th DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Empl oyees i n Department Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Bean wi th SQLJ Code Befor e Transl ati on . . . . . . . . . . . . . . . . . . . . . . 252 SQLJ Code After Transl ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Depl oyment of an SQLJ Servl et to WebSpher e . . . . . . . . . . . . . . . . . . . . . 258 SQLJ Servl et Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261 Appendix A. Odds and Ends. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Di fferent Mappi ng of SQL Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Corr ect Depl oyment of Enter pr i se Beans . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Data Access Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 WebSpher e Studi o. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 Appendix B. Special Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Appendix C. Related Publications. . . . . . . . . . . . . . . . . . . . . . . . . . . 273 I nter nati onal Techni cal Suppor t Or gani zati on Publ i cati ons . . . . . . . . . . . 274 Redbooks on CD-ROMs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Other Publ i cati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 How to Get ITSO Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 I BM Redbook Fax Order Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 List of Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 ITSO Redbook Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Copyright IBM Corp. 1999 ix Figures 1. WebSpher e Admi ni str ator Logi n Panel . . . . . . . . . . . . . . . . . . . . . . . . 6 2. WebSpher e Admi ni str ati on Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3. Servi ces Panel : Star ti ng and Stoppi ng WebSpher e . . . . . . . . . . . . . . . 8 4. Add Feature to Vi sual Age for Java Envi r onment . . . . . . . . . . . . . . . 10 5. Featur e Sel ecti on Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 6. Cl ass Path Setup for the WebSphere Test Envi r onment . . . . . . . . . . 13 7. Sampl e Consol e Output from SERunner . . . . . . . . . . . . . . . . . . . . . . 14 8. Creati ng a New Database usi ng the Contr ol Center . . . . . . . . . . . . . 22 9. Create Database Smar tGui de . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 10. Add User to a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 11. DB2 Tabl e Creati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 12. DB2 Sampl e Data Extract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 13. Creati ng a New User for Oracl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 14. Assi gni ng a Rol e to an Or acl e User . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 15. Or acl e Tabl e Creati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 16. Or acl e Tabl e Creati on Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 17. I mpor t Data For The Empl oyee Tabl e . . . . . . . . . . . . . . . . . . . . . . . . 31 18. Or acl e Sampl e Data Extract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 19. Create a New Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 20. SQL Server Tabl e Cr eati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 21. I mpor t Data for Depar tment Tabl e . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 22. Choose a Desti nati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 23. Sel ect the Desti nati on Tabl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 24. I mpor ti ng Data Was Successful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 25. ODBC Data Sour ce Admi ni strator . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 26. Create New Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 27. Create New Data Source to SQL Server . . . . . . . . . . . . . . . . . . . . . . . 40 28. Create New Data Source to SQL Server (Database Setup) . . . . . . . . 41 29. Categor y 2 JDBC Dr i ver, Vendor Speci fi c Br i dge . . . . . . . . . . . . . . . 44 30. Categor y 3 JDBC Dr i ver, Generi c Network Pr otocol . . . . . . . . . . . . . 45 31. Edi ti ng Vi sual Age for Javas Cl ass Path. . . . . . . . . . . . . . . . . . . . . . . 48 32. JDBC Dr i ver s i n WebSphere Cl ass Path . . . . . . . . . . . . . . . . . . . . . . 49 33. Si mpl e Cl ass for JDBC Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 34. JDBC Exampl e Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 35. DB2 UDB JDBC Code Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 36. Or acl e JDBC Code Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 37. ODBC DSN Author i zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 38. ODBC Data Sour ce Admi ni strator . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 x IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server 39. SQL Server JDBC Exampl e Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 40. Si mpl e Servl et doGet Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 41. Si mpl e Servl et Output i n a Web Browser . . . . . . . . . . . . . . . . . . . . . . 64 42. I nter acti on Fl ow Between the Connecti on Manager and a Servl et. . 66 43. Connecti on Management on WebSpher e . . . . . . . . . . . . . . . . . . . . . . 67 44. Connecti on Pool Confi gur ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 45. HTML for the Connecti on Manager Ser vl et Exampl es . . . . . . . . . . . 71 46. Launchi ng a Servl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 47. Exporti ng a Servl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 48. DbaseConnMgr Cl ass Decl arati on. . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 49. DbaseConnMgr i ni t Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 50. DbaseConnMgr i ni tConnecti on Method . . . . . . . . . . . . . . . . . . . . . . . 74 51. DbaseConnMgr getConnecti on Method. . . . . . . . . . . . . . . . . . . . . . . . 74 52. DbaseConnMgr r el easeConnecti on Method . . . . . . . . . . . . . . . . . . . . 75 53. DBaseConnMgr executeSel ect Method . . . . . . . . . . . . . . . . . . . . . . . . 75 54. DBaseConnMgr outputI nfo Method . . . . . . . . . . . . . . . . . . . . . . . . . . 75 55. doGet Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 56. UdbConnMgr Cl ass Decl arati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 57. UdbConnMgr getDr i ver Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 58. UdbConnMgr getPool Name Method . . . . . . . . . . . . . . . . . . . . . . . . . . 77 59. UdbConnMgr getUrl Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 60. Connecti on Manager Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 61. Or acl eConnMgr Cl ass Decl ar ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 62. Sql SrvConnMgr Cl ass Decl ar ati on . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 63. Data Access Beans Archi tectur e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 64. I nter nal Connecti on Management by DatabaseConnecti on . . . . . . . 84 65. Exter nal Connecti on Management by I BM Connecti onManager . . . 84 66. Sel ect Statement Desi gn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 67. Servl et User I nterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 68. The Ser vl et Pal ette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 69. Servl et wi th Data Access Bean and Sel ect Bean . . . . . . . . . . . . . . . . 88 70. UdbEmpI nDept Connecti on Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 71. Connecti on Al i as Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 72. UdbEmpI nDept SQL Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 73. Creati ng New SQL Speci fi cati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 74. Sel ecti ng a Tabl e for the Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 75. Setti ng Quer y Condi ti on(s) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 76. Sel ecti ng Col umns to I ncl ude for a Quer y . . . . . . . . . . . . . . . . . . . . . 93 77. SQL Quer y Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 78. Resul ti ng SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 79. UDB Servl et Usi ng Data Access Beans: Vi sual Composi ti on . . . . . . 96 80. Tai l ored Method wi th Short Col umns Names . . . . . . . . . . . . . . . . . . 97 81. Output Resul t of the Servl et i n a Web Browser . . . . . . . . . . . . . . . . . 97 xi 82. Empl oyeeServl et Cl ass Decl arati on . . . . . . . . . . . . . . . . . . . . . . . . . . 98 83. Empl oyeeServl et i ni t Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 84. Empl oyeeServl et getParameter Method . . . . . . . . . . . . . . . . . . . . . . 100 85. Empl oyeeServl et doGet and doPost Methods . . . . . . . . . . . . . . . . . . 101 86. Empl oyeeServl et per for mTask Method. . . . . . . . . . . . . . . . . . . . . . . 101 87. Empl oyeeServl et getEmpl oyee Method (I ) . . . . . . . . . . . . . . . . . . . . 102 88. Empl oyeeServl et getEmpl oyee Method (I I ) . . . . . . . . . . . . . . . . . . . 102 89. getEmpl oyee Method (I I I ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 90. Empl oyeeServl et getEmpl oyee Method (I V) . . . . . . . . . . . . . . . . . . . 103 91. Output of the getEmpl oyee Method . . . . . . . . . . . . . . . . . . . . . . . . . 104 92. Empl oyeeServl et getEmpl oyee Method (V). . . . . . . . . . . . . . . . . . . . 104 93. Empl oyeeServl et getEmpl oyee Method (VI ) . . . . . . . . . . . . . . . . . . . 104 94. Empl oyeeServl et updateEmpl oyee Method (I ) . . . . . . . . . . . . . . . . . 105 95. Empl oyeeServl et updateEmpl oyee Method (I I ) . . . . . . . . . . . . . . . . 105 96. Empl oyeeServl et updateEmpl oyee Method (I I I ). . . . . . . . . . . . . . . . 105 97. Empl oyeeServl et updateEmpl oyee Method (I V). . . . . . . . . . . . . . . . 106 98. Empl oyeeServl et updateEmpl oyee Method (I V). . . . . . . . . . . . . . . . 106 99. Properti es for the Empl oyee Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . 107 100. I mpor ti ng a Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 101. I mpor t Tabl e Sel ecti on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 102. Schema Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 103. Schema Col umn Edi tor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 104. Model Br owser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 105. Attr i bute Edi tor : Mar ki ng the Val ue Requi red Fi el d. . . . . . . . . . . . 116 106. Map Browser wi th a Br oken Tabl e Map . . . . . . . . . . . . . . . . . . . . . . 117 107. Model Br owser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 108. Gener ati on Opti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 109. Gener ati on Opti ons (Bean Properti es) . . . . . . . . . . . . . . . . . . . . . . . 119 110. Schema Gener ati on Sel ecti on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 111. Database Connecti on I nfor mati on . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 112. HTML Output Page of a Servl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 113. Vi sual Composi ti on Edi tor wi th Per si stence Bui l der Pal ette . . . . . 123 114. Composi ti on Edi tor wi th Connecti ons . . . . . . . . . . . . . . . . . . . . . . . . 124 115. Col umn I denti fi ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 116. Servl et Test Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 117. Establ i shi ng Connecti ons to Mul ti pl e Database Vendors . . . . . . . . 127 118. Exporti ng the Ser vl et . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 119. WebSpher e Appl i cati on Server: Java Engi ne Setup . . . . . . . . . . . . 129 120. Avai l abl e Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 121. EJB Devel opment Pane: Addi ng an EJB Gr oup. . . . . . . . . . . . . . . . 135 122. EJB Smar tGui de . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 123. Addi ng a Fi el d. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 124. Swi tchi ng to the Fi el ds Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 xii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server 125. Add Methods to the Remote I nterface. . . . . . . . . . . . . . . . . . . . . . . . 139 126. Mar ki ng Properti es Contai ner Managed . . . . . . . . . . . . . . . . . . . . . 140 127. Connecti on I nfor mati on for the Schema I mpor t. . . . . . . . . . . . . . . . 140 128. Sel ect the Tabl e to I mport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 129. Schema Browser after I mpor t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 130. Speci fyi ng the Datastor e Map for the Enterpri se Bean . . . . . . . . . . 142 131. Map Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 132. The Pr oper ty Map Edi tor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 133. EJB Server Confi gurati on Di al og . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 134. EJB Server Pr oper ti es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 135. EJS Consol e Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 136. Test Cl i ent. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 137. The Home I nterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 138. Parameter Speci fi cati on for the DepartmentKey . . . . . . . . . . . . . . . 147 139. Test Cl i ent Presenti ng the Remote I nterface . . . . . . . . . . . . . . . . . . 148 140. WebSpher e Gener al EJB Setti ngs . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 141. WebSpher e Contai ner EJB Setti ngs . . . . . . . . . . . . . . . . . . . . . . . . . 151 142. EJB Jar Fi l e Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 143. Redepl oyment Warni ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 144. Depar tmentEJBServl et Cl ass Decl arati on . . . . . . . . . . . . . . . . . . . . 154 145. Depar tmentEJBServl et perfor mTask Method . . . . . . . . . . . . . . . . . 154 146. Depar tmentEJBServl et i ni t Method . . . . . . . . . . . . . . . . . . . . . . . . . 155 147. Depar tmentEJbServl et getDepartment Method . . . . . . . . . . . . . . . 156 148. Depar tmentEJBServl et createOrFi ndDepartment Method . . . . . . 157 149. Depar tmentEJBServl et updateDepartment Method . . . . . . . . . . . . 158 150. Depar tmentEJBServl et i n a Br owser . . . . . . . . . . . . . . . . . . . . . . . . 159 151. Depar tment Panel wi th Al l Connecti ons . . . . . . . . . . . . . . . . . . . . . 160 152. Depar tmentPanel createOrFi nd Method . . . . . . . . . . . . . . . . . . . . . 162 153. Depar tment Panel Di spl ayi ng the Department Bean . . . . . . . . . . . 163 154. Addi ng a BMP Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 155. Properti es i n the Workspace Vi ew. . . . . . . . . . . . . . . . . . . . . . . . . . . 165 156. Empl oyeeBean ejbFi ndByPri mar yKey Method . . . . . . . . . . . . . . . . 167 157. Empl oyeeBean ejbStor e Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 158. Empl oyeeBean Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 159. Empl oyeeStorage Cl ass Decl arati on . . . . . . . . . . . . . . . . . . . . . . . . . 169 160. I ni ti al i ze the Sel ect Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 161. Empl oyeeBean ejbStor e Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 162. Fi nd an Empl oyee. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 163. Update the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 164. Retri eve and Di spl ay the Empl oyee Bean . . . . . . . . . . . . . . . . . . . . . 175 165. Set the Pr oper ti es of the Empl oyee Bean . . . . . . . . . . . . . . . . . . . . . 176 166. Empl oyeeEJBSer vl et Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 167. Create New Pr oject. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 xiii 168. Speci fy Project Parameter s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 169. WebSpher e Studi o Project Wi ndow . . . . . . . . . . . . . . . . . . . . . . . . . . 182 170. WebSpher e Studi o Tool Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 171. Speci fy a Name for the SQL Statement . . . . . . . . . . . . . . . . . . . . . . 183 172. Speci fy the Connecti on Par ameters . . . . . . . . . . . . . . . . . . . . . . . . . 184 173. Sel ect Tabl es from the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 174. Speci fy the Joi n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 175. Speci fy the Col umns to Di spl ay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 176. Speci fy the Condi ti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 177. Compl eted SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 178. Sel ect the SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 179. Sel ect the Generated Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 180. Speci fy I nput Parameter s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 181. Speci fy the Fi el ds for the Resul t Page. . . . . . . . . . . . . . . . . . . . . . . . 190 182. Speci fy to Use the Bean i n a Sessi on. . . . . . . . . . . . . . . . . . . . . . . . . 191 183. Provi de Package Name and Cl ass Name Pr efi x . . . . . . . . . . . . . . . . 191 184. Fi ni sh the Wi zard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 185. Project after Ser vl et Generati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 186. Speci fy Publ i shi ng Opti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 187. Publ i shi ng Server Pr oper ti es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 188. Publ i shi ng Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 189. Sel ect Previ ew fr om the Context Menu . . . . . . . . . . . . . . . . . . . . . . . 197 190. Gener ated HTML I nput Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 191. Gener ated HTML Output Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 192. Creati ng an I nsert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 193. Sel ect the I nput Fi el ds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 194. Gener ated SQL I nsert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 195. I nser t a New Empl oyee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 196. Sel ect the DEPNO Col umn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 197. WebSpher e Page Desi gner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 198. Speci fy the Ser vl et to be I nvoked . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 199. Speci fy Bean Par ameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 200. Resul ti ng Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 201. Sel ecti ng the Loop Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 202. Gener ated Code for Dynami c I tem Val ues . . . . . . . . . . . . . . . . . . . . 207 203. Enhanced I nsert Servl et I nput Page wi th Combobox . . . . . . . . . . . 209 204. Compl ete Project Vi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 205. Enabl i ng User Pr ofi l e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 206. UserPr ofi l e Database Setup for DB2. . . . . . . . . . . . . . . . . . . . . . . . . 216 207. UserPr ofi l e Database Setup for Or acl e . . . . . . . . . . . . . . . . . . . . . . . 216 208. UserPr ofi l e Database Setup for SQL Server . . . . . . . . . . . . . . . . . . . 217 209. UserPr ofi l es Connecti on Pool Sel ecti on . . . . . . . . . . . . . . . . . . . . . . 217 210. i tsowasdb.user profi l e Cl ass Li sti ng. . . . . . . . . . . . . . . . . . . . . . . . . . 220 xiv IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server 211. UserPr ofi l eCartSer vl et Methods Li sti ng . . . . . . . . . . . . . . . . . . . . . 221 212. UserPr ofi l eCartSer vl et Cl ass Decl ar ati on . . . . . . . . . . . . . . . . . . . . 221 213. UserPr ofi l eCartSer vl et addUserShoppi ngCart Method . . . . . . . . . 222 214. UserPr ofi l eCartSer vl et.cr eateUserPr ofi l e . . . . . . . . . . . . . . . . . . . . 222 215. UserPr ofi l eCartSer vl et doGet Method . . . . . . . . . . . . . . . . . . . . . . . 222 216. UserPr ofi l eCartSer vl et doPost Method. . . . . . . . . . . . . . . . . . . . . . . 223 217. UserPr ofi l eCartSer vl et getPar ameter Method . . . . . . . . . . . . . . . . . 223 218. UserPr ofi l eCartSer vl et i temCr eateToOutputPage Method. . . . . . . 224 219. UserPr ofi l eCartSer vl et performTask Method . . . . . . . . . . . . . . . . . 225 220. UserPr ofi l eCartSer vl et processLogi n Method . . . . . . . . . . . . . . . . . 226 221. UserPr ofi l eCartSer vl et retr i eveUser Pr ofi l e Method . . . . . . . . . . . . 227 222. UserPr ofi l eCartSer vl et user CreateToOutputPage Method . . . . . . . 227 223. UserPr ofi l e Logi n Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 224. UserPr ofi l e UserCreate Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 225. UserPr ofi l e Defaul t OutputPage After User Regi strati on . . . . . . . . 229 226. UserPr ofi l e I temCreate Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 227. UserPr ofi l e Defaul t Output Page After I tem Cr eati on . . . . . . . . . . 230 228. UserPr ofi l eCartSer vl et.Servl et Contr ol Fi l e. . . . . . . . . . . . . . . . . . . 231 229. UserPr ofi l eLogi n.html Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 230. UserPr ofi l eCr eate.jsp Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 231. UserPr ofi l eCartOutputPage.jsp Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . 233 232. I temI nfoI nputPage.jsp Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 233. UserPr ofi l eCartEr ror Page.jsp Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . 234 234. User Profi l es Properti es Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 235. Rel ati onshi ps Between Real m, ACL, and Resour ce . . . . . . . . . . . . . 239 236. WebSpher e Admi ni str ati on Setup for Di r ector y Management . . . . 241 237. WebSpher e Access Contr ol Li st Mai n Panel . . . . . . . . . . . . . . . . . . . 242 238. Addi ng a New Access Contr ol Li st . . . . . . . . . . . . . . . . . . . . . . . . . . 242 239. Add Permi ssi on to ACL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 240. WebSpher e Access Contr ol Li st Mai n Panel wi th New ACL . . . . . . 244 241. WebSpher e Resour ces Secur i ty Setup. . . . . . . . . . . . . . . . . . . . . . . . 244 242. Protect a Resour ce usi ng Di r ector y Servi ce thr ough ACL . . . . . . . . 245 243. Resour ce Panel after Addi ng a Resour ce to be Pr otected. . . . . . . . . 245 244. SQLJ Exampl e Ser vl et (Sql jSer v.java) . . . . . . . . . . . . . . . . . . . . . . . 251 245. SQLJ Exampl e Ser vl et Bean (Sql jSer vBean.sql j) Part 1 . . . . . . . . . 252 246. SQLJ Exampl e Ser vl et Bean (Sql jSer vBean.sql j) Part 2 . . . . . . . . . 253 247. SQLJ Code after Tr ansl ati on: I ter ator Cl ass Defi ni ti on . . . . . . . . . 255 248. SQLJ Code after Tr ansl ati on: Si mpl e Sel ect Statement . . . . . . . . . 256 249. SQLJ Code after Tr ansl ati on: Sel ect Wi thout Resul t Set . . . . . . . . 257 250. WebSpher e Appl i cati on Server: Java Engi ne Setup . . . . . . . . . . . . 258 251. Output of SQLJ Ser vl et Empl oyees i n Depar tment Exampl e . . . . . 259 252. Defaul t Mappi ng for the Empl oyee Tabl e i n DB2 . . . . . . . . . . . . . . 264 253. Defaul t Mappi ng for the Empl oyee Tabl e i n Oracl e . . . . . . . . . . . . . 265 xv 254. Defaul t Mappi ng for the Empl oyee i n ODBC/Sql Server . . . . . . . . . 265 255. WebSpher e Studi o Database Wi zar d . . . . . . . . . . . . . . . . . . . . . . . . 267 xvi IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 xvii Tables 1. Di r ector i es and Fi l es wi th Sampl e Code . . . . . . . . . . . . . . . . . . . . . . . . . 16 2. Model s and Packages i n the Reposi tor y Sampl es. . . . . . . . . . . . . . . . . . 17 3. Properti es of the Empl oyee Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 xviii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 xix Preface Wi th the move of Java appl i cati ons to a servl et r unti me envi r onment on a Web ser ver the access of rel ati onal databases on the Web server becomes one of the most i mportant topi cs. I BM WebSpher e i s a set of softwar e products that hel p customers devel op and manage hi gh-per formance Web si tes to ease the tr ansi ti on from si mpl e Web publ i shi ng to advanced e-busi ness appl i cati ons. Vi sual Age for Java Enter pri se i s the premi er Java i ntegr ated devel opment envi ronment that hel ps customer s connect thei r Java appl i cati ons to thei r enter pr i se data. Vi sual Age for Java pr ovi des an i ntegrated WebSphere Test Envi ronment that makes devel opment and depl oyment of ser vl ets to WebSphere fast and easy. I n thi s r edbook we descri be many ways of how rel ati onal database systems can be i ntegr ated wi th the Vi sual Age for Java devel opment envi ronment and the WebSphere executi on envi r onment. Fi r st, we descri be the i nstal l ati on of the underl yi ng base products I BM WebSphere and Vi sual Age for Java. Next, we descri be the i nstal l ati on and setup of the database systems and JDBC dri vers for the thr ee r el ati onal database management systems DB2 Uni versal Database, Oracl e, and Mi crosoft SQL Server. Fi nal l y, we pr ovi de smal l progr ammi ng exampl es for JDBC, data access beans, the Per si stence Bui l der, Enter pri se JavaBeans, WebSphere Studi o, User Profi l es, Securi ty and Di rector y Servi ces, and SQLJ. Thi s redbook i s especi al l y sui ted for Java appl i cati on desi gners that are i mpl ementi ng servl ets wi th r el ati onal database access. xx IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The Team That Wrote This Redbook Thi s redbook was produced by a team of speci al i sts fr om ar ound the wor l d worki ng at the I nter nati onal Techni cal Support Or gani zati on San Jose Center. Ueli Wahli i s a Consul tant AD Speci al i st at the I BM I nter nati onal Techni cal Suppor t Organi zati on i n San Jose, Cal i forni a. Before joi ni ng the I TSO 14 year s ago, Uel i wor ked i n techni cal support at I BM Swi tzer l and. He wr i tes extensi vel y and teaches I BM cl asses worl dwi de on appl i cati on devel opment, object technol ogy, Vi sual Age products, data di cti onari es, and l i br ary management. Uel i hol ds a degree i n Mathemati cs fr om the Swi ss Feder al I nsti tute of Technol ogy. Hi s e-mai l addr ess i s wahli@us.ibm.com. TobiasHimstedt i s a Seni or Consul tant wor ki ng for SerCon GmbH, an I BM Gl obal Ser vi ce Company i n Mai nz, Germany. Tobi as hol ds a di pl oma i n Computer Sci ence from the Uni versi ty of Hi l deshei m, Germany. He i s co-author of a book about Python, a useful scr i pti ng l anguage. Before joi ni ng SerCon he wor ked for GMD, the German Nati onal Research Center for I nformati on Technol ogy. There, he was mai nl y i nvol ved i n a European resear ch project about el ectroni c commerce. Hi s areas of exper ti se i ncl ude I nter net, cl i ent/server, object-ori ented, and component technol ogi es (e-mai l : tobias.himstedt@sercon.de). Sean Leei s an I T Speci al i st cur rentl y engaged i n customer consul ti ng i n New Yor k. He i s a DB2 Techni cal Speci al i st representi ng the DB2 devel opment l ab i n San Jose, Cal i forni a. Sean has 2 years of exper i ence i n I nformati on Technol ogi es and hol ds a degr ee i n Computer Sci ence fr om the State Uni versi ty of New York i n Bi nghamton. Hi s areas of exper ti se i ncl ude System/390 database management and connecti vi ty. You can contact Sean at leese@us.ibm.com. Amir Razmara i s an I T Speci al i st i n Canada. He has 6 years of exper i ence i n the software devel opment fi el d. He hol ds a degree i n Computer Sci ence from the York Uni ver si ty i n Toronto, Canada. Hi s areas of exper ti se i ncl ude object-or i ented anal ysi s and desi gn, database servers, cl i ent/server and i nter net sol uti ons for e-busi ness. Hi s e-mai l address i s razmara@ca.ibm.com. xxi Thanks to the fol l owi ng peopl e for thei r i nval uabl e contr i buti ons to thi s project: Joaqui n Pi con I nter nati onal Techni cal Support Organi zati on, San Jose Center Moncri ef Rowe-Anderson I BM Santa Teresa Lab (DB2 JDBC SQLJ) Vi r i nder Batr a I BM Ral ei gh Comments Welcome Your comments areimportant to us! We want our redbooks to be as hel pful as possi bl e. Pl ease send us your comments about thi s or other redbooks i n one of the fol l owi ng ways: Fax the eval uati on form found i n I TSO Redbook Eval uati on on page 285 to the fax number shown on the form. Use the onl i ne eval uati on form found at http://www.redbooks.ibm.com Send your comments i n an i nter net note to redbook@us.ibm.com xxii IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 1 Part 1 Introduction to IBM WebSphere and VisualAge for Java I n thi s par t we bri efl y di scuss the i nstal l ati on of the two pr oducts, I BM WebSpher e and Vi sual Age for Java Enterpr i se. 2 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 3 1 HTTP Server and WebSphere Application Server I n thi s chapter we descr i be the I BM HTTP Ser ver and the I BM WebSphere Appl i cati on Server. The functi onal i ty of these pr oducts wi l l be br i efl y di scussed, i ncl udi ng a few hi nts and ti ps on how to set them up to run your servl ets i nsi de and outsi de of the Vi sual Age for Java envi r onment. Environment The exampl es i n thi s book were devel oped i n the fol l owi ng envi r onment: PCs wi th Penti um I I 450 MHZ processors and 128 MB RAM MS Wi ndows NT 4.0 ser vi ce pack 4 Both Netscape Navi gator 4.5 and Mi cr osoft I nternet Expl orer 4.0 were used i nter changeabl y thr ough the test and usage of di ffer ent components. 4 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server IBM HTTP Server I BM HTTP Ser ver i s a Web server whi ch shares i ts base code wi th the Apache Server, wi th addi ti onal enhancements such as the Secur e Socket Layer (SSL). Installation I BM HTTP Ser ver Versi on 1.3.3.1 was used to run the sampl e code pr ovi ded i n thi s book. Be sure to consi der the fol l owi ng dur i ng the i nstal l ati on: Make sur e ther e i s a user I D dedi cated to be used onl y by the HTTP server. The user I D must be a member of the Admi ni str ator gr oup. Once you have cr eated the user I D proceed wi th the i nstal l ati on. As you step thr ough the i nstal l ati on pages enter the user I D created pri or to the i nstal l ati on i nto the I nformation for ServiceSetup panel . Configuration To confi gur e the HTTP ser ver you shoul d use the httpd.doc fi l e l ocated under <drive>:\Program Files\IBM HTTP Server\conf. You can customi ze the HTTP Server usi ng the tags i n httpd.conf fi l e. Here i s a descr i pti on on some of those tags: DocumentRoot: The di rectory where the HTTP Server l ooks for the HTML fi l es. The defaul t set val ue i s <drive>:/Program Files/IBM HTTP Server/htdocs. Alias: To cr eate a speci fi c l ocati on for your project you can take advantage of the Alias tag. Thi s tag can be set to poi nt to any di r ector y wher e you wi sh to pl ace your HTML and JSP fi l es. I f you want to access fi l es whi ch resi de i n a l ocati on other than the DocumentRoot di rector y, you can use an Alias to do thi s. For exampl e, to be abl e to access test.html fr om a c:\i tsowww di r ector y, set Alias /itso/ "C:/itsowww/" i n the httpd.conf fi l e. Thi s way, to access the test.html fi l e from the br owser the fol l owi ng URL shoul d be used: http://<server name>/itso/test.html ServerRoot: The di rectory where the server's confi gur ati on, er ror, and l og fi l es ar e kept. ServerName: I f you observe any pr obl ems wi th the I BM HTTP Server i t mi ght hel p to expl i ci tl y set the server name to your host name. Chapter 1. HTTP Server and WebSphere Application Server 5 IBM WebSphere Application Server The WebSpher e Appl i cati on Ser ver i mpl ements a servl et engi ne that functi ons as a pl ug-i n to extend the capabi l i ti es of a number of Web ser vers. WebSphere i s an appl i cati on server that enabl es the wr i te once, use anywher e concept for ser vl ets. WebSphere can wor k wi th number of di fferent Web ser vers, such as: I BM HTTP Ser ver Apache Ser ver 1.3.x Lotus Domi no 5.0 Lotus Domi no Go Webser ver Netscape Enterpri se Ser ver Netscape FastTr ack Server Mi crosoft I nter net I nformati on Server Al l of the sampl es pr ovi ded i n thi s book have used the I BM HTTP Ser ver as thei r Web ser ver. Wi th a properl y coded URL, cl i ent r equests to a Web server are passed on to the Appl i cati on Server. The Appl i cati on Server, i n turn, passes the cl i ent request i nformati on to a Java ser vl et, whi ch acts on the request i nfor mati on and prepar es a r esponse that i s sent back to the cl i ent through the Appl i cati on Server and the Web server. A Java ser vl et i s basi cal l y an ordi nary pi ece of Java code wi th added capabi l i ti es provi ded by API s i n the javax.servlet and javax.servlet.http packages. These packages are standard Java extensi ons avai l abl e from JavaSoft for JDK 1.1 and bui l t-i n to JDK 1.2. The request/r esponse model i s used by gener al Web browser and server i nter acti ons over the I nter net, and i t appl i es to ser vl et behavi or as wel l . Because HTTP i s a statel ess protocol , one r equest/r esponse knows nothi ng about another request/r esponse, even from the same Web browser, unl ess addi ti onal sessi on state features are added. WebSphere Installation The WebSpher e Appl i cati on Ser ver Versi on 2.02 was used to r un the sampl e code pr ovi ded i n thi s book. One thi ng to consi der pri or to i nstal l ati on i s to make sur e you ar e usi ng a speci fi c I P address i nstead of an I P addr ess pr ovi ded thr ough a DHCP server (we di d experi ence probl ems wi th a DHCP address). 6 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The i nstal l ati on pr ocess for WebSpher e Appl i cati on Ser ver i s fai r l y si mpl e. The onl y thi ng you need to know i s the Web ser ver that i s used wi th WebSphere. I t i s a good i dea to i nstal l the Web ser ver pr i or to i nstal l i ng WebSphere. Al so make sur e you sel ect the ri ght Web server to wor k wi th WebSphere, because ther e i s no easy way to change thi s after the i nstal l ati on. WebSphere Configuration To confi gur e di fferent components of WebSpher e you use the admi ni strati on appl et of WebSpher e. To gai n access on your browser i nput the fol l owi ng URL: http://<server-name>:9527 or http://<ip-address>:9527. Thi s star ts the appl et and di spl ays the mai n admi ni str ator l ogi n panel (Fi gure 1). Figure1. WebSphereAdministrator Login Panel Fr om the admi ni str ati on panel you confi gure di ffer ent components of WebSphere (Fi gure 2). Chapter 1. HTTP Server and WebSphere Application Server 7 Figure2. WebSphereAdministration Panel Servlet and Java Class Files Location The servl et and Java cl ass fi l es shoul d r esi de under: <drive>:\WebSphere\AppServer\servlets\<package name (if any)> or <drive>:\WebSphere\AppServer\classes\<package-name>. Keep i n mi nd that the cl asses pl aced under the servlets di r ectory can be repl aced at any ti me wi thout the need to restart WebSphere. On the other hand, the cl asses pl aced under the classes di r ector y do requi re WebSpher e to be r estar ted when they are r epl aced. Ther efor e, the cl asses di rectory i s the proper pl ace to store any packages that wi l l most l i kel y not change, whi l e the servl ets di rectory i s the best pl ace dur i ng devel opment and testi ng. Servl ets are addressed wi th the URL: http://<server-name>/servlet/packagename.ClassName WebSphere Configuration for JDBC To run a ser vl et wi th JDBC i n WebSphere, we have to make the JDBC dri ver s avai l abl e. See Confi guri ng WebSphere for JDBC on page 49 for detai l ed i nstr ucti ons. 8 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Starting and Stopping WebSphere When usi ng the I BM HTTP server i t i s not necessary to star t WebSpher e expl i ci tl y. Thi s i s done automati cal l y when the HTTP Ser ver i s started. To stop WebSpher e use the Control Panel->Services (Fi gure 3) and stop the WebSphereServlet Service. Next, stop the I BM HTTP Server. To r estart, just star t the I BM HTTP Server agai n and veri fy that the WebSphereServlet Servicei s star ted as wel l . Figure3. Services Panel: Starting and StoppingWebSphere Copyright IBM Corp. 1999 9 2 VisualAge for Java Enterprise Version 2 Because Vi sual Age for Java Ver si on 2 contai ns some very ni ce tool s to devel op, debug, and run servl ets and Enter pri se JavaBeans i n a test envi ronment, Vi sual Age for Java was used to devel op the sampl es. I n thi s chapter we bri efl y descr i be how to i nstal l and confi gure Vi sual Age for Java to work pr oper l y wi th the I BM WebSpher e Test Envi ronment. 10 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server VisualAge for Java Installation The i nstal l ati on consi sts of three steps: 1. I nstal l Vi sual Age for Java ver si on 2.0 GA rel ease, r eboot, star t Vi sual Age for Java, and exi t. 2. I nstal l fi xpack Rol l up 2 by unzi ppi ng the fi l e rollup2_vaj20_win.zip to the Vi sual Age for Java di rectory (c:\IBMVAJava), star t Vi sual Age for Java to compl ete the i nstal l ati on, and exi t. 3. I nstal l the Enter pri se Update, start Vi sual Age for Java, and exi t. Duri ng the i nstal l ati on Vi sual Age for Java asks for the di r ector y for HTML fi l es; the defaul t path i s <drive>:\www\html. Thi s i s the l ocati on wher e the I BM WebSphereTest Environment l ooks for the HTML fi l es. VisualAge for Java Configuration for JDBC To r un Java progr ams wi th JDBC i n Vi sual Age for Java, we have to make the JDBC dri vers avai l abl e. See Confi gur i ng Vi sual Age for Java for JDBC on page 48 for detai l ed i nstructi ons. VisualAge for Java Configuration for WebSphere Once the i nstal l ati on i s compl ete, you shoul d add the I BM WebSphereTest Environment featur e to the Workbench by sel ecti ng Workbench ->File-> Quick Start (Fi gur e 4). Figure4. Add FeaturetoVisualAgefor J ava Environment Chapter 2. VisualAge for Java Enterprise Version 2 11 Sel ect Feature->Add Featureand sel ect I BM WebSphereTest Environment 1.1 (Fi gur e 5). Figure5. FeatureSelection Panel I f the feature has al r eady been added i t wi l l not be l i sted. Addi ng the featur e wi l l al l ow you to r un ser vl ets wi thi n the Vi sual Age for Java envi r onment. WebSphere in VisualAge for Java I n thi s secti on we descr i be the necessary steps i nvol ved i n setti ng up and runni ng ser vl ets i nsi de Vi sual Age for Java. Default Directories for Servlets and JSP files The HTML and JSP fi l es shoul d resi de under : <drive>:\www\html (refer to VisualAgefor J ava I nstallation on page10) The XML ser vl et confi gurati on fi l es (.servl et) shoul d resi de under : <drive>:\IBMVJava\ide\project_resources\<project name>\<[package name]> 12 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Compiled JSPs When the JSP fi l e i s accessed through a servl et i t i s tr ansl ated i nto a Java fi l e and i ts cl ass i s executed i n the Vi sual Age for Java envi r onment. The Java versi on of the JSP fi l e can be found i n the J SP PageCompileGenerated Code project i n the Vi sual Age for Java Workbench. Running Servlets in VisualAge for Java There are a coupl e of steps you have to take to run your Webspher e appl i cati on. From the Workbench sel ect the com.ibm.servlet package i n the I BM WebSphereTest Environment pr oject. Execute the SERunner cl ass to star t the servl et runti me envi r onment. Dependi ng on the pr ocessi ng power of your machi ne thi s wi l l take between 20 to 120 seconds to get star ted. Befor e r unni ng SERunner make sur e the pr oject i n whi ch the ser vl et code i s resi di ng i s i ncl uded i n the cl ass path of SERunner (Fi gure 6). One safe opti on i s to sel ect al l the pr ojects and add them to the cl ass path of the SERunner cl ass. To run JSPs, the J SP PageCompileGenerated Codeproject must al so be added to the cl ass path. Thi s pr oject does not exi st ori gi nal l y; i t i s cr eated when the fi rst JSP i s compi l ed. Onl y then can the pr oject be added to the cl ass path of the SERunner cl ass. Chapter 2. VisualAge for Java Enterprise Version 2 13 Figure6. Class Path Setup for theWebSphereTest Environment When the WebSphere test envi r onment i s up and r unni ng you can l aunch your servl ets by sel ecti ng the servl et cl ass and Tools ->Servlet Launcher -> Launch from the context menu. I f the SERunner i s not runni ng, thi s pr ocess wi l l l aunch the SERunner. After SERunner i s l aunched, a seri es of messages i s di spl ayed i n the Consol e wi ndow of Vi sual Age for Java. At some poi nt a message ServerProcess: Server startedgets l ogged. Despi te what the message i ndi cates, the server does some further processi ng befor e i t i s ful l y 14 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server oper ati onal . Fi gur e 7 shows the fi nal message i n the Consol e wi ndow that i ndi cate the server i s trul y up and runni ng. Figure7. SampleConsoleOutput fromSERunner Checking if server is already started on port: 8080 ***Starting WebSphere Test Environment*** ServerProcess: Start services ServiceManager: Load service adminservice . . . . Servlet reloading is disabled ServiceManager: Autostarting servletservice ServiceManager: Autostarting httpservice ServerProcess: Server started. . . . servletservice: Load (update): endpoint.main.port=80 ServiceParameters: servletservice: Load (update): endpoint.main.port=80 Copyright IBM Corp. 1999 15 3 ITSO Sample Applications The sampl e code devel oped for thi s book i s avai l abl e as a ZI P fi l e on the I nter net: ftp://www.redbooks.ibm.com/redbooks/SG245471/ The 5471samp.zi p fi l e expands i nto a di rectory str ucture contai ni ng al l the sampl e code: \WasDbBk\Code <=== sample files for book chapters \WasDbBk\Code\Repository <=== VisualAge for Java export files (.dat) 16 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Sample Code Tabl e 1 descr i bes the sampl e code subdi r ector y structur e and the fi l es contai ned i n those subdi rectori es. Table1. Directories and Files with SampleCode Subdirectory Files Description Mai n di r ectory: \WasDbBk\Code DBase xxx.ddl Database defi ni ti on DDL for DB2, Or acl e, and SQL Ser ver xxx.i cx, xxx.csv Sampl e tabl e data l oad fi l es Reposi tor y xxx.dat Vi sual Age for Java r eposi tor y expor t fi l e i tso\wasdb\..pkg xxx.cl ass, xxx.java Vi sual Age for Java expor ted cl asses, matchi ng the package str uctur e depl oyabl eEJBs xxx.jar Vi sual Age for Java jar fi l es for depl oyment of EJBs to WebSphere Html xxx.html HTML, JSP, and ser vl et XML fi l es Studi o xxx.war WebSphere Studi o archi ve fi l e xxx.java, .html , .jsp, .servl et, .sql WebSphere Studi o gener ated fi l es Chapter 3. ITSO Sample Applications 17 Repository Export Files The r eposi tory subdi r ector y (\WasDbBk\code\Repository) contai ns one fi l e: 5426samp.dat (contains project ITSO SG24 5471) Tabl e 2 descr i bes the sampl es that we devel oped and the reposi tor y packages wher e the code i s stor ed. Table2. Models and Packages in theRepository Samples To l oad the packages i nto the r eposi tory, use the i mport functi on of Vi sual Age for Java. You can i mport the whol e projects or just i ndi vi dual packages. After i mporti ng you have to l oad the packages i nto the Workbench, ei ther i nto your own project or by usi ng the I TSO SG24 5471 pr oject. Package Description itso.wasdb.jdbc JDBC exampl e and ser vl et exampl e itso.wasdb.connmgr Connecti on manager exampl e itso.wasdb.accessbean Data access bean exampl e itso.wasdb.connaccess Data access bean wi th connecti on manager itso.wasdb.persist.metadata Per si stence Bui l der model , schema, map itso.wasdb.persist Per si stence Bui l der domai n cl asses itso.wasdb.persist.Services Per si stence Bui l der ser vi ce cl asses itso.wasdb.persist.gui Per si stence Bui l der GUI appl i cati on itso.wasdb.ejb Enter pr i se JavaBeans itso.wasdb.ejb.client Enter pr i se JavaBeans cl i ent exampl e itso.wasdb.ejb.servlet Enter pr i se JavaBeans servl et exampl e itso.wasdb.studio WebSphere Studi o exampl e itso.wasdb.userprofile WebSphere user profi l e exampl e itso.wasdb.sqlj DB2 SQLJ exampl e ITSO_EJ BsEJ BReserved Enter pr i se JavaBeans contr ol i nformati on 18 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 19 Part 2 Database Setup and JDBC I n thi s par t we di scuss the i nstal l ati on and setup requi r ed for al l of the rel ati onal database pr oducts and the setup requi red to create a JDBC connecti on to your database. I n our project we used thr ee di ffer ent r el ati onal database management systems, together wi th the WebSpher e Appl i cati on Ser ver, WebSpher e Studi o, and Vi sual Age for Java DB2 UDB Versi on 5.2 Or acl e 8i , Versi on 8.0.4 Mi crosoft SQL Server, ver si on 7.0 20 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 21 4 Relational Database Installation and Setup I n thi s chapter we descr i be the i nstal l ati on and setup of the r el ati onal database pr oducts used for the exampl es throughout thi s book. For the pur pose of the sampl es pr ovi ded, al l of the databases do shar e the same name and tabl e formats. Because the scr i pts used to cr eate these databases wer e sl i ghtl y di fferent, al l three scr i pts are posted here. To standardi ze the data str uctur es accessed i n each of the database pr oducts, we cr eated a si mpl e sampl e database cal l ed I TSOWDB to run quer i es agai nst. We created a schema under the I D I TSO. Ther efor e al l of the tabl e names used are I TSO.<TABLENAME>. The sampl e data defi ni ti on l anguage (DDL) or SQL fi l e for every database i s l i sted under the corr espondi ng i nstal l ati on secti on. 22 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server DB2 UDB Installation We i nstal l ed DB2 Uni ver sal Database for Wi ndows NT Ver si on 5.2. To keep the ver si on curr ent, UDB fi xpack WR09074, al so known as fi xpack 6, was i nstal l ed. To use the SQLJ functi onal i ty, you must i nstal l fi xpack 8 (see Chapter 14, Usi ng SQLJ to Access a Database on page 247). DB2 UDB Database Setup After DB2 i s i nstal l ed, you need to cr eate the I TSOWDB database. You can ei ther use a GUI wi th the DB2 Control Center or use a DB2 command wi ndow. I f you are usi ng the Control Center, you sel ect Systems ->[ComputerName] -> I nstances ->DB2 ->Databases. Open the context menu (r i ght cl i ck) and sel ect Create->New (Fi gure 8). Figure8. Creating a NewDatabaseusing theControl Center A SmartGui de prompts you for the database name (Fi gure 9). For the pur pose of our sampl e code, you do not have to use the other pages of the Smar tGui de di al og. Enter the name and cl i ck on Done. Chapter 4. Relational Database Installation and Setup 23 Figure9. CreateDatabaseSmartGuide I f you are usi ng a DB2 Command Wi ndow run the command: db2 create database itsowdb I f you want to fi nd out more about the createdatabaseopti ons, enter: db2 ? create database Thi s command l i sts al l of the opti ons avai l abl e for the parti cul ar DB2 command. User ID By conventi on we create al l tabl es under the I TSO user I D (wi th the password itso). Because of thi s you need to add the I TSO user I D to the database user l i st. Make sure that the user I D I TSO i s al r eady created i n the Wi ndows NT oper ati ng system. The si mpl est way to to add the user I D to the database i s through the Contr ol Center. Sel ect the I TSOWDB database and open User and Group Objects. I n the context menu (ri ght mouse cl i ck) sel ect DB Users and sel ect Add. Fr om the Add User panel sel ect theI TSO user I D and gi ve i t al l of the Authorities. Then cl i ck on Apply and then on Close(Fi gur e 10). 24 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure10. Add User toa Database DB2 UDB Table Creation When the database i s created, the next step i s to create the tabl es i n the database. Fi gur e 11 shows the itsowdb.ddl fi l e fi l e used to create the tabl es. To execute thi s fi l e, open a DB2 Command Wi ndow and r un the command: db2 -tvf itsowdb.ddl Use the pr oper di r ector y (c:\WasDbBk\dbase\db2) for the scr i pt fi l e. Two tabl es are cr eated: Depar tment Empl oyee These tabl es defi ni ti ons are si mi l ar to the tabl es of the DB2 SAMPLE database. We deci ded not to use the SAMPLE database, so that we can have the same database and tabl es i n al l thr ee database systems. Chapter 4. Relational Database Installation and Setup 25 Figure11. DB2 TableCreation 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.DEPARTMENT ADD 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.EMPLOYEE ADD 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; 26 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Loading the Table Data Into DB2 The l oad statements at the bottom of Fi gur e 11 l oad the sampl e data i nto the tabl es from a data fi l e that uses one l i ne of comma-del i mi ted data for each row of the tabl es. An extr act of the sampl e data (.csv fi l es) i s shown i n Fi gure 12. Figure12. DB2 SampleData Extract DB2 JDBC Drivers The DB2 JDBC dri vers ar e i n the c:\SQLLIB\java\db2java.zip fi l e. Thi s fi l e must be avai l abl e to Java thr ough the cl ass 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 Chapter 4. Relational Database Installation and Setup 27 Oracle 8 Installation We have i nstal l ed a standar d devel oper i nstal l ati on of Or acl e Ver si on 8.0.4 under Wi ndows NT. Oracle Database Setup We assume that Or acl e i s i nstal l ed. We are now goi ng to create the tabl es of the itsowdb database, and fi l l the tabl es wi th sampl e data. User ID By conventi on, al l tabl es ar e created under the I TSO user I D, so the fi rst thi ng to do i s to create the I TSO user. To do that, open the Oracl e 8 Navi gator. I n the tr ee go al l the way down to the User node (Fi gure 13). I n the General Pane cr eate the user I TSO wi th password itso; i n the Privileges Pane gi ve the new I TSO user addi ti onal l y the ResourceRol e (Fi gure 14). I n our i nstal l ati on the Or acl e i nstal l er di d not copy the JDBC dri ver fi l es. Make sur e those dri ver fi l es are i nstal l ed i f you pl an to access an Oracl e database usi ng JDBC. We copi ed the dr i ver fi l es manual l y from the i nstal l ati on CD fr om win32/v8/Jdbc to c:\orant\Jdbc, whi ch was the home of our Or acl e8 i nstal l ati on. Moreover, i f you l ater want to use the OCI Dri ver (see Or acl e OCI Dr i ver on page 46) you ei ther have to put c:\orant\Jdbc\lib i n the system path or pl ace the oci804jdbc.dll somewhere i n the path, for exampl e, c:\WinNT\system32. Notice 28 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure13. Creatinga New User for Oracle Figure14. Assigninga Roleto an OracleUser Chapter 4. Relational Database Installation and Setup 29 Oracle Table Creation Now that the user i s cr eated, the next step i s to cr eate the database tabl es. You wi l l noti ce that we have not yet cr eated a database oursel ves. Duri ng the i nstal l ati on of Or acl e, a database i s created that hol ds al l the tabl es. Fi gur e 15 l i sts the SQL statements used to create the I TSOWDB tabl es. Figure15. OracleTableCreation 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; 30 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server To cr eate the tabl es, start the SQL Plus 8.0 tool from the Start menu. Connect as user I TSO wi th passwor d itso. You wi l l use the itsowdb.ddl fi l e from the Oracl e di r ector y. Fr om the SQL>pr ompt, i ssue the command: start c:\WasDbBk\dbase\Oracle\itsowdb.ddl Use the corr ect path for the SQL fi l e for your i nstal l ati on. Fi gure 16 di spl ays the resul t when you i ssue the start command to execute the SQL. Figure16. OracleTableCreation Output Now your tabl es are set up to i mport the actual data. To do that, use the Oracle8 Navigator agai n. Expand the tree unti l you see the new tabl es i n the l ocal databases. You shoul d have at l east one tabl e named DEPARTMENT and one named EMPLOYEE. Because the defaul t i nstal l ati on of Or acl e8 i nstal l s tabl es wi th the same names, make sure you i mport the data to the cor rect tabl es. Veri fy thi s by i nspecti ng that owner of the tabl es i s I TSO. Chapter 4. Relational Database Installation and Setup 31 Importing the Table Data into Oracle I mpor t the data by sel ecti ng I mport FromFile(Fi gur e 17). Then speci fy the data fi l e, whi ch i s ei ther employee.csv for the empl oyee tabl e or department.csv for the department tabl e. Both fi l es r esi de i n the same di rectory as the itsowdb.ddl fi l e (c:\WasDbBk\dbase\Oracle). Figure17. I mport Data For TheEmployeeTable The sampl e data fi l es ar e al most i denti cal to the fi l es used for DB2. An extr act of the sampl e data i s shown i n Fi gure 18. The for mat of the date col umns i s di ffer ent, 01-JAN-1965 i nstead of 1965-01-01. To di sti ngui sh r esul ts of quer i es, we use empl oyee numbers starti ng wi th the number 1, that i s, 100010 i nstead of 000010. 32 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure18. OracleSampleData Extract The database i s now r eady. You may veri fy thi s by sel ecti ng one of the tabl es (ri ght cl i ck) and open i t. Oracle JDBC Drivers The Or acl e JDBC dr i ver s are i n the c:\orant\jdbc\lib\classes111.zip fi l e. Thi s fi l e must be avai l abl e to Java through the cl ass 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-194 5", 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 Chapter 4. Relational Database Installation and Setup 33 SQL Server Installation We i nstal l ed SQL Ser ver Versi on 7.0 Desktop. Befor e you pr oceed wi th the i nstal l ati on you shoul d go to the I nstallation Pre-requisitesecti on. Check and make sur e the I nternet Explorer ver si on you have i s equal or greater than the versi on menti oned i n the pre-r equi si te. I f you have an ol der versi on, proceed wi th the pr erequi si te i nstal l ati on and then go and i nstal l the SQL ser ver. SQL Server Database Setup There ar e a few steps you must fol l ow to enabl e access to SQL Server thr ough WebSphere. Because SQL Server does not provi de a JDBC dri ver, we use the Sun JDBC/ODBC br i dge to get a connecti on to the database. Create ITSOWDB Database The fi r st step i s to create our database: Open the SQL Ser ver Enter pri se Manager. Expand ConsoleRoot ->Microsoft SQL Server ->SQL Server Group -> [Computer-Name] ->Databases and sel ect NewDatabasefrom the context menu (Fi gur e 19). Figure19. Createa New Database 34 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Now enter the database name I TSOWDB i n the Name: entr y fi el d and cl i ck OK. Setup User ID as Owner To cr eate the database tabl es wi th the I TSO schema you have to add the I TSO user I D i nto the l i st of Logins as fol l ows: Fr om Enterpri se Manager expand ConsoleRoot ->Microsoft SQL Server -> SQL Server Group ->[Computer-Name] and open Security. Ri ght mouse cl i ck on Logins and sel ect New Login. I nput I TSO as the Nameand sel ect your Domain under Authentication. Under Defaults for Databasesel ect I TSOWDB. Sel ect Server Roles tab and check SystemAdministrators. Sel ect DatabaseAccess, check I TSOWDB and check public and db_owner as databaseroles. Now cl i ck on the OK button. SQL Server Table Creation To cr eate the tabl es for SQL Ser ver we run the DDL commands i n the c:\WasDbBk\dbase\SQLServer\itsowdb.ddl fi l e. To run thi s fi l e you have to r un the Query Analyzer. Thi s i s a separ ate SQL Server tool found from Wi ndows Start ->Programs ->SQL Server, or from the SQL Server Enterprisemanager sel ect Tools ->SQL Query Analyzer. Open the fi l e and run i t (Fi gure 20). Make sur e to sel ect the I TSOWDB database from the l i st of databases on the top menu bar. Chapter 4. Relational Database Installation and Setup 35 Figure20. SQL Server TableCreation Importing the Table Data into SQL Server We now have to fi l l our tabl es wi th content. The easi est way to do thi s i s to use the i mport/export wi zard. From the Microsoft SQL Server 7.0 pr ogram gr oup star t I mport and Export Data. Ski p the entry panel wi th the i ntroducti on text and pr oceed 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.DEPARTMENT ADD 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.EMPLOYEE ADD PRIMARY KEY (EMPNO); ----------------- DDL Statement for foreign key relationship ALTER TABLE ITSO.EMPLOYEE ADD FOREIGN KEY (WORKDEPT) REFERENCES ITSO.DEPARTMENT (DEPTNO); 36 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Make sur e you sel ect Text Fileas the sour ce. Then speci fy the path (c:\WasDbBk\dbase\SQLServer) where the csv fi l es are l ocated (Fi gure 21). Figure21. I mport Data for Department Table I n the next panel you may speci fy the fi l e format of the text fi l e that i s to be i mpor ted. I t shoul d not be necessary to make any changes. Then you may speci fy the col umn separ ator. Agai n the defaul t shoul d be suffi ci ent. Fi gur e 22 shows the next step. Be sure to sel ect the cor rect database as the i mport desti nati on. Chapter 4. Relational Database Installation and Setup 37 Figure22. Choosea Destination Now the desti nati on tabl e has to be speci fi ed. I n thi s case we i mpor t the department data i nto the depar tment tabl e as desti nati on (Fi gur e 23). Figure23. Select theDestination Table I n the next step you may speci fy addi ti onal opti ons, for exampl e, i f thi s i mport process shoul d be stor ed. We ski p thi s step and cl i ck Next. The wi zar d shows i ts l ast panel , i nfor mi ng us that the i mpor t pr ocess i s now speci fi ed and ready to r un. Cl i ck Finish. I f everythi ng r uns fi ne, SQL Server wi l l i nfor m you wi th a message box (Fi gur e 24). 38 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure24. I mporting Data Was Successful The same i mpor t has to be performed for the empl oyee tabl e usi ng the employee.csv fi l e. The sampl e data fi l es ar e i denti cal to the fi l es used for Oracl e (Fi gur e 18 on page 32), wi th the excepti on that we used empl oyee numbers starti ng wi th the number 2, that i s, 200010 i nstead of 100010. SQL Server JDBC Drivers SQL Server does not provi de JDBC dr i vers. We use the JDBC/ODBC bri dge dri ver s provi ded by Sun i n the JDK. To use the br i dge we have to set up an ODBC data source. ODBC Data Source Setup for JDBC To enabl e the I TSOWDB database for ODBC or for the JDBC/ODBC br i dge, you have to set up an ODBC data source: Go to the Control Panel and open ODBC Data Sources. I n the ODBC Data Sour ce Admi ni strator sel ect the SystemDSN tab (Fi gure 25). Chapter 4. Relational Database Installation and Setup 39 Figure25. ODBC Data SourceAdministrator Sel ect Add to add a new DSN (Fi gur e 26). Figure26. CreateNewData Source 40 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Sel ect SQLServer and cl i ck on Finish. Enter the name, descri pti on, and ser ver for the Data Source Name, then cl i ck Next (Fi gur e 27). Figure27. CreateNewData SourcetoSQL Server Now speci fy what ki nd of author i zati on you want the database to use and then cl i ck on Next. Next you sel ect the I TSOWDB database for the ODBC connecti on. Cl i ck on Next (Fi gur e 28). Chapter 4. Relational Database Installation and Setup 41 Figure28. CreateNewData SourcetoSQL Server (DatabaseSetup) On the ODBC Microsoft SQL Server SetupPanel cl i ck on Test Data Source to confi r m that your sel ecti ons wer e cor rect and that the connecti on can be establ i shed. Then cl i ck on Finish. You must make sur e to set up a System DSN and not a User DSN. I f you set up a User DSN you wi l l not be abl e to establ i sh a connecti on to SQL server thr ough WebSpher e, because i t i s usi ng a defaul t systemI D to gai n access. Note 42 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 43 5 Java Database Connectivity Sun devel oped the Java Database Connecti vi ty (JDBC) data access l ayer to keep the Java API for accessi ng rel ati onal databases standard acr oss al l vendor s. Si mi l ar to Mi cr osofts ODBC, thi s l ayer pr ovi des Java progr ammers a generi c way to communi cate wi th rel ati onal databases regar dl ess of the database vendor. Most vendor s provi de JDBC dri vers for thei r pr oducts, whi ch enabl es you to access the vendor s database usi ng the JDBC API . For mor e detai l ed i nfor mati on on JDBC dri vers and categori es of dr i ver s, r efer to the I BM redbook Application Development with VisualAgefor J ava Enterprise, SG24-5081. 44 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server DB2 UDB JDBC Drivers I BM provi des two JDBC dr i vers for standar d access to DB2. Each was devel oped by uti l i zi ng pr evi ousl y wr i tten softwar e, so each i mpl ements the connecti on di ffer entl y. The dri vers ar e shi pped wi th DB2 UDB and ar e l ocated i n the fi l e: c:\SQLLIB\java\db2java.zip When testi ng your JDBC appl i cati ons, thi s fi l e must be accessi bl e i n the Java cl ass path, or your appl i cati on wi l l not be abl e to fi nd the JDBC dr i ver s. DB2 Application Driver The DB2 appl i cati on dri ver i s i n the COM.i bm.db2.j dbc.app.DB2Dri ver cl as s, l ocated i n the db2j ava.zi p cl ass col l ecti on fi l e. Thi s dr i v er us es th e URL for mat of jdbc:db2:<database name> (jdbc:db2:itsowdb) Known as a category (or type) 2 JDBC dr i ver, thi s dr i ver takes advantage of a previ ousl y wr i tten database cl i ent softwar e. I t contai ns a JDBC br i dge that cl oses the gap between the new Java coded dri ver and the l egacy cl i ent access software. The br i dge takes JDBC commands and transl ates them i nto the tradi ti onal commands used i n the cl i ent softwar e. I n DB2s case, the DB2 Cl i ent Appl i cati on Enabl er (CAE) i s used (Fi gure 29). The JDBC dri vers must have CAE code l i br ari es avai l abl e to access the ser ver. Figure29. Category 2 J DBC Driver, Vendor Specific Bridge When the JDBC br i dge accesses CAE code, the cl i ent i s accessi ng non-Java code l i brar i es. Thi s dr i ver i s not used for communi cati on between cl i ent and CLIENT SERVER Application JDBC Driver Manager JDBC Vendor Specific Data Access Bridge Client Application Enabler (CAE) DBMS Server Chapter 5. Java Database Connectivity 45 server acr oss a networ k because of i ts use of pl atfor m dependent code. Thi s i s because you cannot package the non-Java, pl atform speci fi c code, i nto a JAR fi l e to send to a cl i ent when the cl i ent requests di r ect access to an i ndependent database server. DB2 Network Driver The networ k dri ver i s i n the COM.ibm.db2.jdbc.net.DB2Driver cl ass, al so l ocated i n the db2java.zi p cl ass col l ecti on. I t has a URL of the format: jdbc:db2://<hostname>:<port>/<database> (jdbc:db2://sonoma:6789/itsowdb) Thi s dri ver i s known as a category 3 JDBC dr i ver, whi ch spl i ts the dri ver code between the cl i ent and the ser ver. The cl i ent contai ns the pure Java code and the ser ver contai ns the pl atform speci fi c code. When a database cal l i s i ssued, the cl i ent tr ansl ates the cal l i nto a generi c networ k protocol . The server then transl ates the cal l back i nto a JDBC cal l and processes the cal l on the server. Because the cl i ent i s pure Java, thi s i s a good i mpl ementati on for networ k use (Fi gure 30). Figure30. Category 3 J DBC Driver, Generic Network Protocol These dr i ver s requi re softwar e on the ser ver, al so known as mi ddl eware, to ful fi l l the database request and return the resul t to the cl i ent; for DB2 thi s i s the DB2 JDBC appl et ser ver. You must star t thi s ser vi ce on the ser ver from the Services menu i n the Control Panel, i t uses the defaul t port number of 6789. You can al so start i t from a DOS command pr ompt by i ssui ng the command: db2jstrt <port number> (db2jstrt 6789) JDBC Driver Manager JDBC Generic Network Protocol Driver Middleware Middleware DBMS (DB2) DBMS (other) Application 46 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Oracle JDBC Drivers Or acl e pr ovi des two categori es of JDBC, a thi n cl i ent dr i ver whi ch i s pure Java and a second dri ver known as the Oracl e Cal l I nter face (OCI ) dr i ver. The OCI dr i ver i s not pur e Java and uses pl atform-speci fi c nati ve methods to access the database. Both dri vers ar e i mpl emented i n the oracle.jdbc.driver.OracleDriver cl ass. Oracle Thin Client Driver The thi n cl i ent dri ver i s a type 4 cl i ent dr i ver whi ch r equi r es onl y sockets to connect to an Oracl e database. The dri ver i s compl etel y i mpl emented i n Java, so i t i s pl atfor m neutr al and does not r equi r e any Or acl e softwar e to be i nstal l ed on the cl i ent. A type 4, accordi ng to the defi ni ti on of JavaSoft, i s a native-protocol fully J ava technology-enabled driver. The URL to access a database thr ough the thi n cl i ent i s: jdbc:oracle:thin:@<servername>:<portnumber>:<databasename> I n our exampl es we use the defaul t database i nstance orcl and the defaul t port number 1521, therefore the resul ti ng URL i s: jdbc:oracle:thin:@localhost:1521:orcl Oracle OCI Driver The OCI dri ver i s a type 2 dr i ver. By defi ni ti on a categor y 2, or type 2, dr i ver i s a native-API partly J ava technology-enabled driver (as shown i n Fi gur e 29 on page 44). I t pr ovi des an i mpl ementati on of the JDBC based on the nati ve OCI to access the database. Si nce nati ve methods ar e used to i nter act wi th the database, the OCI dr i ver i s pl atform speci fi c. Al though thi s dr i ver i s not sui tabl e for appl ets, the OCI dri ver has the advantage of better per for mance. Thi s makes i t i deal for bei ng used by ser vl ets on the server. As we tested, both dr i ver s work wi th WebSphere, pr ovi ded that the Appl i cati on Server cl ass path i ncl udes the Or acl e dr i ver s, and that for the OCI dr i ver the oci804jdbc.dll fi l e i s i n the system path (see Oracl e 8 I nstal l ati on on page 27). Chapter 5. Java Database Connectivity 47 The URL to access a database usi ng the OCI dri ver i s somewhat l onger: jdbc:oracle:oci8:@(description=(address=(host=<servername>) (protocol=tcp)(port=<portnumber>))(connect_data= (sid=<databasename>))) I n our exampl es we use the defaul t database i nstance orcl and the defaul t port number 1521, therefore the resul ti ng URL i s: jdbc:oracle:oci8:@(description=(address=(host=localhost) (protocol=tcp)(port=1521))(connect_data=(sid=orcl))) SQL Server JDBC Drivers Mi crosoft does not pr ovi de a JDBC dr i ver for SQL Server. JavaSoft does package a JDBC/ODBC br i dge i n the sun.jdbc.odbc.J dbcOdbcDriver cl ass. I t uses a URL for mat of jdbc:odbc:<ODBC Data Source Name>. Suns dri ver does have a few shortcomi ngs; i t i s a type 2 dr i ver, whi ch means i t cannot be used i n appl ets. Al so i t can onl y connect to l ocal ODBC Data Source Names. An ODBC Data Sour ce i s a system defi ned way for a dr i ver to connect to an ODBC compl i ant data pr ovi der. To use ODBC dr i ver s (or a JDBC/ODBC bri dge), you must defi ne an ODBC Data Source Name (DSN) for the data provi der (for exampl e, SQL Server) so that your dri ver knows how to r etri eve i nfor mati on from the data provi der. I n Wi ndows, you can defi ne an ODBC Data Source Name (DSN) by usi ng the ODBC Data Sour ce Admi ni strator, l ocated i n the Wi ndows Control Panel. I t i s possi bl e to defi ne a DSN on your machi ne for a r emote server, but access must be granted on the server for your speci fi c machi ne name. Many vendors offer dr i vers whi ch can connect di r ectl y to remote ser ver s, but most requi re some mi ddl eware to transl ate the cal l s fr om JDBC to ODBC. A company named i -net softwar e (www.inetsoftware.de) does offer s a categor y 4 dri ver for SQL Ser ver. Thi s dri ver has made a posi ti ve i mpr essi on on the Java communi ty, but we have nei ther tested nor i mpl emented thi s pr oduct. A category 4 dri ver i s a pure Java dr i ver that connects di r ectl y to the ser ver and does not r equi r e any ODBC setup or use. Categor y 4 dr i ver s ar e the most preferr ed dri vers. 48 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Configuring VisualAge for Java for JDBC To use the databases from wi thi n the devel opment envi ronment of Vi sual Age for Java, the dr i vers have to be made vi si bl e i n Vi sual Age for Java. There are two ways to achi eve thi s. The fi r st possi bi l i ty i s to i ncl ude the zi p fi l es contai ni ng the JDBC dr i vers i n the cl ass path of Vi sual Age for Java: The DB2 zi p fi l e i s c:\sqllib\java\db2java.zip The Oracl e zi p fi l e i s c:\orant\Jdbc\lib\classes111.zip The JDBC/ODBC br i dge for SQL Ser ver i s par t of the standard Sun Java cl asses. To add the zi p fi l es to the cl ass path, open the Options di al og from the Window menu i n Vi sual Age for Java. Cl i ck on Resources on the l eft si de and edi t the Workspaceclass path on the ri ght si de, as i n Fi gure 31. Figure31. Editing VisualAgefor J avas Class Path C:\sqllib\db2java.zip;c:\orant\Jdbc\lib\classes111.zip; Chapter 5. Java Database Connectivity 49 The second possi bi l i ty i s to i mpor t the zi p fi l es i nto the r eposi tory and Workbench of Vi sual Age for Java. Thi s has the advantage that, i f l ater on an appl i cati on or an appl et i s packed together wi th the r equi r ed JDBC dr i ver s, Vi sual Age for Java wi l l be abl e to i ncl ude the dri ver s i n the resul ti ng JAR fi l es. To i mport the zi p fi l e use the i mpor t feature. Sel ect File->I mport and sel ect J ar-fileas i nput source, br owse for the jar fi l e (ei ther db2java.zip or classes111.zip) and i mpor t i t, for exampl e under the new project Database J DBC Drivers. Configuring WebSphere for JDBC To use the DB2 and Oracl e JDBC dr i vers for ser vl ets wi thi n WebSphere i t i s necessar y to i ncl ude the dri ver cl asses i n the WebSpher e cl ass path. Open a Web br owser wi th the WebSpher e admi ni strati on page (http://<server-name or ip-address>:9527), go to Setup ->J ava Engine, and add c:\sqllib\java\db2java.zip (DB2) c:\orant\Jdbc\lib\classes111.zip (Oracle) to the Application Server Classpath Entr y (Fi gure 32). Figure32. J DBC Drivers in WebSphereClass Path 50 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 51 Part 3 Database Programming Examples Thi s par t descr i bes al l of the code i mpl ementati ons of i ntegrati ng Websphere, Vi sual Age for Java, and database managers. These exampl es are si mpl i fi ed to faci l i tate your understandi ng of the concepts. After r evi ewi ng these exampl es you shoul d have devel oped the basi c knowl edge necessary to i ntegrate Websphere Java servl ets and database management systems i n more compl ex envi r onments. For al l of the devel opment and tests that ar e not automated by WebSphere Studi o, we used I BMs Vi sual Age for Java. We recommend the use of thi s devel opment sui te for i ts power, ease of use, and i ts ti ght i ntegr ati on wi th WebSphere. Thi s ti ght i ntegrati on pr ovi des seaml ess por tabi l i ty of your code between the two products. 52 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 53 6 JDBC Programming Examples Thi s chapter bri efl y descri bes, thr ough exampl es, the basi cs of connecti ng Java appl i cati ons and ser vl ets to databases usi ng JDBC. These exampl es shoul d mer el y be used as bui l di ng bl ocks and to understand the concepts. Simple JDBC Application We i mpl emented a si mpl e cl ass to handl e the common i nter acti on wi th each vendor s databases. Thi s cl ass, shown i n Fi gure 33, was i mpl emented usi ng Vi sual Age for Java and cr eated under the itso.wasdb.jdbc package. The pr ogram l ogi c uses the fol l owi ng methods: makeConnection: cr eates a connecti on to the database, pri nts a message to the consol e sayi ng the connecti on was successful , and then r etur ns the connecti on to the cal l er. 54 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure33. SimpleClass for J DBC Access package itso.wasdb.jdbc; import java.sql.*; public class SimpleSQL { // 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 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);} } } Chapter 6. JDBC Programming Examples 55 setXXX: methods to set the database connecti on parameter s. executeSQL: executes an SQL statement and di spl ays the r esul t set to the consol e. Thi s SQL statement performs an i nner joi n of the two tabl es based on the empl oyees depar tment. I t di spl ays the empl oyee number, l ast name, wor k department, and the department managers empl oyee number, as shown i n the output (Fi gur e 34). Note that for thi s si mpl i fi ed exampl e, we are not catchi ng al l possi bl e excepti ons. Figure34. J DBC ExampleOutput Connected to Database: jdbc:db2:itsowdb EMPNO LASTNAME DEPT MGRNO 000010 HAAS SPIFFY COMPUTER SERVICE DIV. 000010 000120 O'CONNELL SPIFFY COMPUTER SERVICE DIV. 000010 000110 LUCCHESSI SPIFFY COMPUTER SERVICE DIV. 000010 000020 THOMPSON PLANNING 000020 000030 KWAN INFORMATION CENTER 000030 000140 NICHOLLS INFORMATION CENTER 000030 000130 QUINTANA INFORMATION CENTER 000030 000060 STERN MANUFACTURING SYSTEMS 000060 000220 LUTZ MANUFACTURING SYSTEMS 000060 000210 JONES MANUFACTURING SYSTEMS 000060 000200 BROWN MANUFACTURING SYSTEMS 000060 000190 WALKER MANUFACTURING SYSTEMS 000060 000180 SCOUTTEN MANUFACTURING SYSTEMS 000060 000170 YOSHIMURA MANUFACTURING SYSTEMS 000060 000160 PIANKA MANUFACTURING SYSTEMS 000060 000150 ADAMSON MANUFACTURING SYSTEMS 000060 000070 PULASKI ADMINISTRATION SYSTEMS 000070 000270 PEREZ ADMINISTRATION SYSTEMS 000070 000260 JOHNSON ADMINISTRATION SYSTEMS 000070 000250 SMITH ADMINISTRATION SYSTEMS 000070 000240 MARINO ADMINISTRATION SYSTEMS 000070 000230 JEFFERSON ADMINISTRATION SYSTEMS 000070 000050 GEYER SUPPORT SERVICES 000050 000090 HENDERSON OPERATIONS 000090 000310 SETRIGHT OPERATIONS 000090 000300 SMITH OPERATIONS 000090 000290 PARKER OPERATIONS 000090 000280 SCHNEIDER OPERATIONS 000090 000100 SPENSER SOFTWARE SUPPORT 000100 000340 GOUNOT SOFTWARE SUPPORT 000100 000330 LEE SOFTWARE SUPPORT 000100 000320 MEHTA SOFTWARE SUPPORT 000100 56 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server DB2 Universal Database JDBC Code Example We use both the appl i cati on dri ver (com.ibm.db2.jdbc.app.DB2Driver) and the network dr i ver (com.ibm.db2.jdbc.net.DB2Driver) i n Fi gure 35 to i l l ustr ate the codi ng of each dr i ver. For the network dri ver, you must remember to star t the JDBC appl et ser ver on the server machi ne. Thi s networ k dri ver uses a gener i c network pr otocol to send i ts request to the ser ver, then pl atform speci fi c code on the ser ver transl ates the cal l to the database manager. See DB2 Network Dri ver on page 45 for further detai l s. The por t speci fi ed i n the networ k dri vers URL must corr espond to the port defi ned when the mi ddl eware on the server (DB2 JDBC appl et ser ver ) i s star ted. Figure35. DB2 UDB J DBC CodeExample 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); } } Chapter 6. JDBC Programming Examples 57 Oracle JDBC Code Example The Oracl e exampl e i s str ai ghtforwar d and di ffers onl y i n the usage of the dri ver s. We used both Oracl e JDBC dr i ver s (Fi gure 36). We assume a standard i nstal l ati on of Or acl e wi th the defaul t setti ngs: The Oracl e ser ver i s l ocated on the same machi ne wher e the exampl e i s runni ng. I f Or acl e i s runni ng on another machi ne, localhost must be repl aced by the name of the appropri ate machi ne. The database i nstance i s the defaul t i nstance whi ch i s created duri ng i nstal l ati on of Or acl e, namel y orcl. I f other database i nstances are used, thi s i s to be repl aced by the appropr i ate names. The defaul t por t number 1521 i s used for the Oracl e ser ver l i stener. Thi s can be changed i n the OracleNet8 Assistant tool . Figure36. OracleJ DBC CodeExample 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); } } } 58 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server SQL Server JDBC Code Example We deci ded to use Suns JDBC/ODBC br i dge dr i ver for our exampl e. I t provi des l i mi ted functi onal i ty but i s suffi ci ent for our testi ng. When usi ng a JDBC/ODBC Bri dge, i t i s i mpor tant to create an ODBC Data Sour ce Name (DSN) for your data ser ver. I n Wi ndows NT, go to the Control Panel and sel ect ODBC Data Sources. Because we ar e usi ng Suns dri ver, we must use a user DSN to access our database. I n the Data Sour ces panel , sel ect the Add button to add a DSN for SQL Server. A prompt for the data source wi l l appear, and i f SQL Server i s i nstal l ed, i t wi l l be l i sted as a possi bl e sour ce. You must speci fy a name, descr i pti on, and a ser ver. You can enter a r emote ser ver by enter i ng the remote server computer name. Thi s i s the onl y way to connect to a r emote server i f you are usi ng Suns dr i ver. The next scr een wi l l prompt you on how to check the author i ty of a l ogi n I D. For remote server authenti cati on you shoul d sel ect SQL Server for author i zati on as i n Fi gure 37. You shoul d al so add thi s I D to the SQL Server r unni ng on the remote computer. Figure37. ODBC DSN Authorization The r est of the setup i s sel f-expl anator y; we chose the defaul t setti ngs for al l other panel s. When you ar e done, you shoul d have a new Data Source Name. I n Fi gur e 38 we have al ready added a l ocal and remote SQL Ser ver. Chapter 6. JDBC Programming Examples 59 Figure38. ODBC Data SourceAdministrator Fi gur e 39 contai ns the cl ass we used to connect to SQL Server. We i nstanti ate the dri ver and then set our par ameters. Noti ce that our URL uses the JDBC/ODBC bri dge standar d nami ng conventi on: jdbc:odbc:<server name>:<Data Source Name> Figure39. SQL Server J DBC ExampleCode 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); } } } 60 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Running Applications with JDBC The sampl e JDBC appl i cati ons can be tested i n Vi sual Age for Java, and they can be run outsi de of Vi sual Age for Java i n the oper ati ng system. Testing the JDBC Applications in VisualAge for Java To execute the sampl e appl i cati ons i n Vi sual Age for Java, make sur e that the JDBC dri vers ar e i n the cl ass path. See Confi guri ng Vi sual Age for Java for JDBC on page 48 for detai l ed i nstr ucti ons. Sel ect the Java cl ass of the appl i cati on and cl i ck on the Run i con i n the tool bar. You can al so sel ect Run ->Run main fr om the context menu. The output of the appl i cati on i s di spl ayed i n the Vi sual Age for Java Consol e wi ndow. Note: The Oracl e OCI dri ver does not work i n Vi sual Age for Java. I t seems that the r equi r ed DLL cannot be l oaded. Running the JDBC Applications in the Operating System A Java JDK must be i nstal l ed i n the oper ati ng system. To run the sampl e appl i cati ons, expor t the cl asses from Vi sual Age for Java i nto a di r ector y that i s i n the Java cl ass path of the operati ng system. We expor ted the cl asses i nto the c:\WasDbBk\code di rectory. Thi s oper ati on cr eates subdi rector i es matchi ng the package name of the cl asses, that i s, c:\WasDbBk\code\itso\wasdb\jdbc. Class Path for Java Applications The cl ass path must i ncl ude the JDBC dri ver s and the exported code. We changed the oper ati ng system CLASSPATH envi r onment vari abl e from the Control Panel ->Systemi con to i ncl ude: c:\sqllib\java\db2java.zip c:\orant\jdbc\lib\classes111.zip c:\WasDbBk\code Run the JDBC Application To execute the JDBC appl i cati ons, open a command wi ndow and enter : java itso.wasdb.jdbc.Db2SQL java itso.wasdb.jdbc.OracleSQL java itso.wasdb.jdbc.SqlSrvSQL Chapter 6. JDBC Programming Examples 61 Simple JDBC Servlet We i mpl emented a si mpl e JDBC ser vl et to gai n exper i ence wi th the WebSphere Test Envi ronment of Vi sual Age for Java and wi th depl oyment of the code to the WebSphere Appl i cati on Server. Our servl et consi sts of two cl asses: DbServletBean: a bean that contai ns al l the JDBC code to l i st the empl oyees of the empl oyee tabl e. DbServlet: a ser vl et that accepts a par ameter to sel ect the database management system and then cal l s the bean to execute the JDBC code. The servl et (DbServl et) contai ns a doGet method that i s cal l ed fr om the Web servers ser vl et engi ne (Fi gure 40). The servl et sets up the bean wi th the JDBC dr i ver, URL, user I D, and password, before cal l i ng the execute method to r un the JDBC code. A parameter named database i s passed to the ser vl et to sel ect the database management system (DB2, Or acl e, or SQLServer). The JDBC bean (DbSer vl etBean) contai ns the fol l owi ng methods: setURL: to set the val ue of the database URL setUserI D: to set the user I D for the connecti on setPassword: to set the passwor d for the connecti on makeConnection: to connect to the database usi ng the URL, user I D, and password executeSQL: to execute the sel ect statement: select empno, lastname, deptname, mgrno from itso.employee A, itso.department B where A.workdept = B.deptno outputI nfo: to create the HTML tabl e wi th the resul t of the sel ect We do not show the code of the JDBC bean her e because i t i s very si mi l ar to the si mpl e JDBC appl i cati on. The onl y di fference i s that the output i s r outed back to the Web ser ver i nstead of bei ng wri tten to the consol e. 62 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure40. SimpleServlet 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>"); } } Chapter 6. JDBC Programming Examples 63 Testing the Servlet in VisualAge for Java Star t the WebSpher e Test Envi ronment (r evi ew Runni ng Ser vl ets i n Vi sual Age for Java on page 12). To run the servl et you open a Netscape br owser and enter the URL: http://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=DB2 http://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=Oracle http://localhost:8080/servlet/itso.wasdb.jdbc.DbServlet?database=SQLServer Al ternati vel y you can set up the ser vl et database parameter through the servl et l auncher pr oper ti es di al og i n Vi sual Age for Java (sel ect the ser vl et cl ass and Tools ->Servlet Launcher ->Properties). Enter the par ameter name (database) and the val ue (DB2, Oracl e, or SQLSer ver). Then l aunch the servl et by sel ecti ng Tools ->Servlet Launcher ->Launch. Thi s star ts a Web browser wi th the corr ect URL. The output of the ser vl et i s shown i n Fi gur e 41. Running the Servlet in WebSphere To depl oy the ser vl et to WebSpher e expor t the cl asses to the WebSpher e servl ets di rectory (c:\WebSphere\AppServer\servlets). Make sur e that the JDBC dri vers ar e i n the WebSphere cl ass path (revi ew WebSphere Confi gurati on for JDBC on page 7). Open a Web browser and enter the URL: http://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=DB2 http://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=Oracle http://<hostname>/servlet/itso.wasdb.jdbc.DbServlet?database=SQLServer The output of the ser vl et i s shown i n Fi gur e 41. 64 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure41. SimpleServlet Output in a Web Browser Copyright IBM Corp. 1999 65 7 IBM Connection Manager The i ntr oductor y text i n thi s chapter i s r epri nted fr om the December 1998 i ssue of the I BM Developer Connection Technical Magazine. The connecti on manager provi des the means to manage pool (s) of connecti ons to one or more database(s). I t cl asses ar e made of wr apper cl asses ar ound the cl asses over java.sql cl asses. Havi ng these wrapper cl asses, JDBC connecti ons are passed to appl i cati ons requesti ng connecti on. The goal of the connecti on manager i s to r educe the per centage of resources used by the nonproducti ve connect/di sconnect overhead, so that these resources ar e avai l abl e to handl e more traffi c. The connecti on manager al so provi des a way to al l ocate r el ati onal database resour ces so that duri ng peak request vol umes the more cr i ti cal servl ets have greater access to the database r esour ces than l ess cr i ti cal ser vl ets. Perfor mance and scal abi l i ty ar e two of the most advantages of the connecti on manager. A servl et needi ng a connecti on to a rel ati onal database wi l l get an exi sti ng connecti on from the pool , thr ough the connecti on manager, r ather than havi ng to create a new connecti on on i ts own. Thi s i s the key to the connecti on manager 's r ol e: connecti ons are kept open and are reused, so the 66 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server connect/di sconnect overhead i s spr ead over many, enti rel y separ ate user requests comi ng i n over the I nter net. WebSpher e makes the connecti on pool management scal abl e by al l owi ng the connecti on pool parameter s to be modi fi ed dynami cal l y. Fi gur e 42 shows the i nteracti on between the connecti on manager and a ser vl et. Figure42. I nteraction FlowBetween theConnection Manager and a Servlet Servl ets whi ch ar e usi ng the connecti on manager can run i nsi de Vi sual Age for Java usi ng the WebSpher e Test Envi ronment or outsi de usi ng WebSpher e i tsel f. Chapter 7. IBM Connection Manager 67 Configuration The connecti on pool s are confi gur abl e thr ough the WebSpher e Appl i cati on Server Admi ni str ator panel (Fi gure 43). For i nformati on on how to get to the Admi ni strator panel pl ease r efer to WebSphere Confi gur ati on on page 6. Figure43. Connection Management on WebSphere Connection Pool There i s a set of pre-defi ned connecti on pool s pr ovi ded as defaul t for database servers such as: I BM DB2 Or acl e I nformi x Mi crosoft SQL Server Sybase You can customi ze your pool by addi ng a new one to the l i st or edi t an exi sti ng one (Fi gure 44). I t i s al so possi bl e to add mul ti pl e entr i es di ffer i ng i n the pool name for di ffer ent databases of the same vendor. Thi s i s even more l i kel y. For exampl e, one coul d add a pool entry speci fyi ng that the database(s) addressed by thi s 68 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server pool have l onger l asti ng ti me out than other databases, addr essed by other pool entr i es, because the user i nter acti on i n a transacti on i s l onger. Figure44. Connection Pool Configuration These are the parameter s that can be set for the connecti on pool : Pool Type: The type of data ser ver used by thi s pool of connecti ons. JDBC i ndi cates a JDBC-compl i ant database. A data ser ver i s a pr oduct that hel ps you manage and access data. Usual l y, i t i s a r el ati onal DBMS such as DB2, Or acl e, I nfor mi x, or Sybase. Pool Name: The uni que name for thi s pool of connecti ons. Servl et progr ammers need to know thi s name for thei r ser vl ets to use thi s connecti on pool . MaximumConnections: Maxi mum number of connecti ons that can be i n the pool . Consi der setti ng i t to the maxi mum number of user s per mi tted by your DBMS product l i cense agr eement. MinimumConnections: The mi ni mum number of connecti ons that can remai n i n the pool as a resul t of the reap process. The connecti on manager peri odi cal l y removes connecti ons that become i dl e or or phaned. Use thi s setti ng to keep fr om removi ng too many connecti ons, er asi ng resource usage performance gai ns. Connection TimeOut: The l ength of ti me (i n mi l l i seconds) the connecti on manager wi l l wai t for a connecti on to become fr ee when al l connecti ons i n the pool ar e curr entl y i n use and the number of connecti ons has reached the maxi mum (meani ng no new connecti ons can be cr eated to ful fi l l the need). Chapter 7. IBM Connection Manager 69 A val ue of 0 al l ows the connecti on manager to wai t for ever. A val ue of -1 di sabl es the wai t (an excepti on i s i mmedi atel y thr own i f a connecti on i s not avai l abl e). A val ue of 1000 to 2000 (1 to 2 seconds) i s suggested. Servl et pr ogrammers must know the val ue of the connecti on ti me out to effecti vel y set the waitRetry parameter i n thei r ser vl ets. MaximumAge: The maxi mum number of seconds a connecti on can be i dl e befor e the reap pr ocess rel eases the connecti on fr om the servl et that owns i t. A val ue of -1 di sabl es thi s functi on; the reap process wi l l not rel ease any connecti ons from i dl e ser vl ets. A val ue of 900 to 1800 (15 to 30 mi nutes) i s suggested. MaximumIdleTime: The maxi mum number of seconds an unassi gned connecti on can r emai n i n the pool . A val ue of -1 di sabl es thi s functi on; the reap process wi l l not remove any connecti on fr om the pool and di sconnect i t from the data ser ver. A val ue of 900 to 1800 (15 to 30 mi nutes) i s suggested. Reap Time: The i nter val (i n seconds) at whi ch the connecti on manager performs the r eap process. A val ue of -1 di sabl es thi s functi on; the reap wi l l not be per formed, regardl ess of the val ues speci fi ed i n Maxi mum Age or Maxi mum I dl e Ti me parameter s. A val ue of 1800 to 3600 (30 to 60 mi nutes) i s suggested. IBM Connection Manager and Pure JDBC When usi ng standar d JDBC for database connecti on, you ar e r esponsi bl e for cr eati ng a new connecti ng to the database and then cl osi ng i t. Once the connecti on i s cl osed, the next tr ansacti on wi l l have to create a new connecti on to access the database. When usi ng the I BM connecti on manager you get a connecti on fr om a connecti on pool . I f a connecti on i s avai l abl e the connecti on manager wi l l return a I BMJ dbcConnection from whi ch you can obtai n i ts under l yi ng JDBC connecti on. When you are done usi ng the connecti on, you do not cl ose the connecti on; you mer el y rel ease i t. Thi s way i t can be used by the next party r equesti ng a connecti on to a database. The connecti on obtai ned thr ough connecti on manager shoul d not be cl osed, that i s, do not call Connection.close. 70 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server IBM Connection Manager Examples I n our programmi ng exampl es we have made connecti ons through the connecti on manager usi ng servl ets. A sel ect query i s r un agai nst the employeetabl e and the r esul t i s di spl ayed on a page usi ng HTML. The connecti ons have been made to thr ee di fferent databases: I BM DB2 Or acl e SQL Server Ever y database exampl e has i ts own cl ass. Al l of the cl asses rel ated to the connecti on manager exampl e ar e par t of the itso.wasdb.connmgr package. The exampl e for al l three databases performs the same task. As a r esul t, al l thr ee cl asses do i nheri t thei r common functi on fr om a super cl ass. The super cl ass name i s DbaseConnMgr. When descr i bi ng the code, onl y the segments that ar e rel evant to the connecti on manager usage ar e descri bed. The rest i s l eft to the readers abi l i ty to r ead the code and under stand i ts pur pose. Using the IBM Connection Manager The package i n whi ch the connecti on manager cl asses r esi de i s ibm.servlet.connmgr. There are sever al steps you must fol l ow to use the connecti on manager. Create a connecti on speci fi cati on usi ng I BMJ dbcConnSpec. Get a reference to the connecti on manager object usi ng the stati c method I BMConnMgrUtil.getI BMConnMgr. Get an I BMJ dbcConn object, that i s, a wr apper around a JDBC connecti on, usi ng the connecti on managers getI BMConnection method. Get a java.sql.Connection Object usi ng getJ dbcConnection of the cl ass I BMJ dbcConn. Now you have a connecti on to the database for your transacti ons. Once you ar e done wi th the tr ansacti on, you have to rel ease the connecti on to be r etur ned i nto the pool . You do thi s by cal l i ng the releaseI BMConnection method of the I BMJ dbcConnection cl ass. Chapter 7. IBM Connection Manager 71 HTML File for Accessing the Servlets A si mpl e HTML fi l e i s used to pr ovi de access to l aunch the servl ets thr ough WebSphere (Fi gure 45). You have to use thi s fi l e onl y when you are tr yi ng to l aunch the ser vl ets outsi de of Vi sual Age for Java. Figure45. HTML for theConnection 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> <A HREF="/servlet/itso.wasdb.connmgr.UdbConnMgr" TARGET="_blank">Run IBM DB2 UDB Sample</A> <br> <A HREF="/servlet/itso.wasdb.connmgr.SqlSrvConnMgr" TARGET="_blank">Run MS SqlServer Sample</A> <br> <A HREF="/servlet/itso.wasdb.connmgr.OrclConnMgr" TARGET="_blank">Run Oracle Sample</A> <br> </td> </tr></table> </BODY> </HTML> Keep i n mi nd that the connecti ons pr ovi ded thr ough the connecti on manager are subject to ti me-outs, dependi ng on the maxi mum age parameter. I f the di fference i n the ti me when you have obtai ned the connecti on and the ti me when you ar e goi ng to use i t i s rather l ong, compar e i t to maxi mum age. I t i s recommended to use verifyI BMConnection pr i or to usi ng the connecti on. I f the ser vl et sti l l owns the connecti on, the method returns true. Other wi se fal se wi l l be r etur ned and you have to obtai n a new connecti on object. Notice 72 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Running the Example There are two ways i n whi ch you can run thi s sampl e: 1. Usi ng the WebSpher e Test Envi ronment i n Vi sual Age for Java Sel ect the servl et cl ass, for exampl e itso.wasdb.connmgr.UdbConnMgr, and l aunch i t from the context menu usi ng Tools ->Servlet Launcher -> Launch (Fi gure 46). Figure46. Launchinga Servlet 2. Usi ng WebSpher e and the HTTP Server Pl ace the ConnMgrTest.html and the UdbConnMgr.class fi l e under the pr oper di r ector i es. The HTML fi l e has to be pl aced i n the path wher e the Web ser ver can fi nd i t. Usi ng the defaul t i nstal l ati on the HTML fi l e shoul d be pl aced under c:\Program Files\IBM HTTP Server\htdocs. The cl ass fi l e can easi l y exported wi th Vi sual Age for Java. Fr om the context menu of the ser vl et cl ass sel ect Export.... I n the fol l owi ng di al og sel ect Directory for the export desti nati on, cl i ck Next and speci fy the export path. I f you use the defaul t i nstal l ati on of WebSpher e thi s i s c:\WebSphere\AppServer\servlets. Make sur e you sel ect at l east the cl ass fi l e to be exported (Fi gure 47). Chapter 7. IBM Connection Manager 73 For more i nfor mati on about the pr oper di r ector y l ocati on r efer to Confi gur ati on on page 4 and WebSphere Confi gurati on on page 6. Figure47. Exportinga Servlet Next go to http://<server-name>/ConnMgrTest.html fr om the HTML page and sel ect the database sampl e you wi sh to r un (you have to export al l servl et exampl es fi rst). DbaseConnMgr Class Thi s cl ass takes care of al l functi on di rectl y i nvol ved wi th the connecti on manager. The fol l owi ng i s the cl ass decl ar ati on for the DbaseConnMgr cl ass (Fi gure 48). We then used subcl asses for the thr ee di fferent DBMSs. Figure48. DbaseConnMgr Class Declaration The init method i ni ti al i zez the servl et when i t i s fi rst l oaded (Fi gure 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"; } 74 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure49. DbaseConnMgr init Method The initConnection method creates a connecti on manager speci fi cati on and obtai ns a stati c r efer ence to the connecti on manager object (Fi gure 50). Figure50. DbaseConnMgr initConnection Method The getConnection method gets an I BMJ dbcConnection object from the connecti on pool and r etur ns a java.sql.Connection. Thi s connecti on i s used for the actual SQL statement (Fi gure 51). Figure51. DbaseConnMgr getConnection Method The releaseConnection method rel eases the I BMJ dbcConnection object i nto the connecti on pool (Fi gure 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; } Chapter 7. IBM Connection Manager 75 Figure52. DbaseConnMgr releaseConnection Method The executeSelect method creates an SQL statement usi ng the connecti on obtai ned from the connecti on manager and executes i t. The resul t of the executi on i s passed on to an output formatti ng r outi ne (Fi gur e 53). Figure53. DBaseConnMgr executeSelect Method The outputI nfomethod r eads the Resul tSet pr oduced by the executeSelect method and pl aces i t i nsi de a tabl e on the HTML page (Fi gure 54). Figure54. DBaseConnMgr outputI nfoMethod The doGet method i s cal l ed from the Web server when the ser vl et i s star ted from the HTML page (Fi gure 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>"); } 76 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure55. 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 thr ee databases menti oned bel ow i s the same, wi th the excepti on of the constants used to descr i be thei r database, connecti on pool , and dri ver name. To avoi d repeti ti on we wi l l revi ew al l the methods for DB2 and wi l l go through speci fi cs of the other two databases. Note Chapter 7. IBM Connection Manager 77 DB2 Befor e you star t make sur e your database i s set up pr oper l y, see DB2 UDB I nstal l ati on on page 22 for more i nformati on. The package i n whi ch the connecti on manager cl asses r esi de i s ibm.servlet.connmgr. The fol l owi ng i s the cl ass decl ar ati on for the UdbConnMgr cl ass. I t i s here where the constants for the speci fi c database and connecti on pool are speci fi ed (Fi gure 56). Figure56. UdbConnMgr Class Declaration The getDriver method returns the JDBC dri ver name (Fi gure 57). Figure57. UdbConnMgr getDriver Method The getPoolNamemethod returns the pool name (Fi gure 58). Figure58. UdbConnMgr getPoolNameMethod 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; } 78 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The getUrl method returns the URL (Fi gure 59). Figure59. UdbConnMgr getUrl Method Sample Output The r esul t of the run of thi s servl et i s shown i n Fi gure 60. Figure60. Connection Manager Output public String getUrl() { return DB2_URL; } Chapter 7. IBM Connection Manager 79 Oracle Befor e you star t make sur e your database i s set up pr oper l y (see Oracl e 8 I nstal l ati on on page 27). The fol l owi ng i s the cl ass decl arati on for the OracleConnMgr cl ass. Her e i s wher e the constants for the speci fi c database and connecti on pool ar e speci fi ed (Fi gure 61). Figure61. OracleConnMgr Class Declaration The r est of the code i s the same as that descri bed i n DB2 on page 77. The onl y di ffer ence i s that, i nsi de the code, the DB2_ constants are r epl aced wi th the ORACLE_ set of constants. Microsoft SQL Server Befor e you star t, make sure your database i s set up properl y (see SQL Server I nstal l ati on on page 33). The fol l owi ng i s the cl ass decl arati on for the SqlSrvConnMgr cl ass. Her e i s wher e the constants for the speci fi c database and connecti on pool ar e speci fi ed (Fi gure 62). Figure62. SqlSrvConnMgr Class Declaration The r est of the code i s the same as that descri bed i n DB2 on page 77. The onl y di ffer ence i s that, i nsi de the code, the DB2_ constants are r epl aced wi th SQLSRV_ 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"; } 80 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 81 8 Data Access Beans: VisualAge for Java I n thi s chapter we descr i be the I BM data access beans and thei r usage thr ough WebSpher e. For mor e detai l ed readi ng, r efer to VisualAgefor J ava EnterpriseVersion 2: Data Access Beans - Servlets - CI CS Connector, SG24-5265. Data access beans provi de access to r el ati onal data. Usi ng data access beans i s the fastest, non-pr ogrammi ng way of bui l di ng SQL quer i es accessi ng exi sti ng databases. Just open the Vi sual Composi ti on Edi tor, pl ace a Sel ect bean on the free-for m sur face, speci fy the database connecti on and data you requi re, and you are ready. Most functi onal i ty i s pr edefi ned. For exampl e, your appl i cati on can add, update, and del ete rows, commi t or r ol l back database tr ansacti ons, handl e mul ti pl e connecti ons, l ock r ows, make the access read onl y, and speci fy how many r ows ar e fetched i nto memory (cache). An SQL Assi st Smar tGui de hel ps you to vi sual l y speci fy the data you need. You can sel ect one or mor e tabl es, joi n tabl es, defi ne search condi ti ons, restri ct the number of col umns, sort the resul t set, and change the mappi ng between the SQL types i n the database and the Java types i n the appl i cati on. 82 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server I n addi ti on, an SQL Edi tor l ets you enter SQL statements manual l y. Use thi s method when you need to compose very speci al or very sophi sti cated database queri es. 1 After you have defi ned your database access usi ng a Sel ect bean, you can pl ace a DBNavi gator bean i nto your vi sual appl i cati on. The DBNavi gator bean i ncor por ates buttons that navi gate the resul t set of a query and per for m var i ous r el ati onal database oper ati ons. The Sel ect bean fi ts i nto the JTabl e model of the new Java Foundati on Cl asses (JFC, cal l ed Swi ng). Thi s rel ati onshi p between retr i eved SQL data and the Swi ng tabl e model makes i t very easy to devel op attr acti ve user i nter faces for Java appl ets and appl i cati ons, based on standard Java cl asses. Wi th data access beans you have di rect access to any database for whi ch a JDK 1.1 compl i ant JDBC dri ver exi sts, for exampl e, DB2 Uni versal Database (UDB) Ver si on 5. 2 Al ter nati vel y, you can use an ODBC dri ver together wi th the JDBC ODBC bri dge that comes wi th the Sun JDK. Loading the Data Access Bean Feature Befor e you can use data access beans you have to add the data access bean featur e to the Workbench. Use the Qui ck Star t menu (F2), sel ect Features -> Add feature, and sel ect I BM Data Access Beans 1.0 i n the di al og that i s di spl ayed. Thi s acti on l oads the project i nto the Wor kbench and adds the data access beans to the beans pal ette of the Vi sual Composi ti on Edi tor. Data Access Beans and the Standard SQL Classes When usi ng java.sql.* set of cl asses, you are r equi r ed to wr i te al l of the SQL code whi ch someti mes can be a headache. Data access beans r equi r e l ess use of SQL and more Java. The fol l owi ng shows the si mi l ar i ti es between java.sql.* cl asses and data access beans (com.ibm.db.*) cl asses (Fi gur e 63). 1 SQL Edi tor gener ated code, i n contr ast to SQL Assi stant gener ated code, cannot handl e SQL par ameters (host var i abl es) because the statement i s not par sed. The devel oper or the appl i cati on code can add the par ameter defi ni ti ons manual l y to the gener ated methods to enabl e passi ng of val ues i nto the host var i abl es. 2 You can al so use DB2 V2.12, pl us the l atest CSD. Chapter 8. Data Access Beans: VisualAge for Java 83 Figure63. Data Access Beans Architecture DatabaseConnection and java.sql.Connection DatabaseConnection i s a r epl acement for java.sql.Connection. I t provi des the same methods as i ts java.sql.Connection counter par t. The connecti on can be managed i nternal l y or exter nal l y dependi ng on whi ch constr uctor i s used. Internal Connection The DatabaseConnection defaul t constructor pr ovi des a wrappi ng object around the JDBC connecti on for i nternal connecti on management. The i nter nal management i s r ather si mpl e. The connecti on that i s cr eated i s shared by any appl i cati on that makes a request to create a connecti on of the same name; i t can connect and disconnect fr om the database at any ti me. Wi th ever y request a counter gets i ncremented i nter nal l y, and as objects disconnect, the counter i s decr emented. The object i s rel eased once the counter i s dropped back to 0 (Fi gure 64). Thi s way mul ti pl e appl i cati ons share the same connecti on. Havi ng thi s i nter nal connecti on management i s i deal for query based appl i cati ons. I f you are usi ng an i nternal connecti on for update, you shoul d be awar e of al l the appl i cati ons wi th access to the connecti on, because any appl i cati on wi th the connecti on can execute a commit or a rollback at any ti me. I f you have sever al beans wi th access to same connecti on you have to ensure the sequence of access to the connecti on to prevent any l oss or dupl i cati on of data. Data Access Beans Architecture Connection Statement PreparedStatement DatabaseConnection ResultSet SelectResult SelectStatement com.ibm.db.* java.sql.* 84 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure64. I nternal Connection Management by DatabaseConnection External Connection When usi ng the DatabaseConnection (java.sql.Connection) constructor, the connecti on i s consi der ed to be exter nal l y managed. You can get thi s connecti on object from some other external l y managed connecti on pool , such as I BMs connecti on manager. You cannot i ssue the connect or disconnect methods agai nst an external l y managed connecti on (Fi gur e 65). Figure65. External Connection Management by I BM ConnectionManager DatabaseConnection java.sql.Connection conn Application Application Application B A C Once all three applications disconnect() the object conn is closed. DatabaseConnection java.sql.Connection connA DatabaseConnection java.sql.Connection connB DatabaseConnection java.sql.Connection connC JdbcDb2 JdbcOracle ConnectionManager DB2 Oracle Chapter 8. Data Access Beans: VisualAge for Java 85 Statement Types The cl ass com.ibm.db.SelectStatement r epr esents an SQL sel ect statement, whi ch i s roughl y equi val ent to both java.sql.Statement and java.sql.PreparedStatement cl asses. The SelectStatement al ways wor ks wi th a hel per object; an i nstance of com.ibm.db.StatementMetaData. Fi gur e 66 shows the way i n whi ch these objects ar e constr ucted. A SelectStatement hol ds a StatementMetaData. A StatementMetaData i s composed of SQL quer y text and col umn i nformati on. Note that mul ti pl e SelectStatements can shar e the same StatementMetaData, the i nfor mati on i s read onl y from that per specti ve. Figure66. Select Statement Design ResultSet Types There are cer tai n drawbacks i n usi ng JDBC di r ectl y; the java.sql.ResultSet can onl y scrol l for ward, not backwar d. The com.ibm.db.SelectResult cl ass of the data access beans i s tr aversabl e both backwar d and forwards, and i t al so al l ows jumpi ng to a parti cul ar i ndex. The SelectResult i s al ready posi ti oned at the fi rst r ow. The SelectResult reads the content of ResultSet i nto i ts str uctur e. The SelectResult has the per for mance hi t the fi rst ti me i t does that. The advantage of the SelectResult becomes apparent when ther e i s a need to scrol l up and down the ResultSet sever al ti mes. SelectStatement StatementMetaData SQL Query Text Column Typing Information 86 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Building a Servlet using Data Access Beans We chose to use the Servlet Builder i n Vi sual Age for Java to create our sampl es. There are thr ee sampl es i n whi ch each of them accesses a di ffer ent DBMS: DB2, Or acl e and SQL Server. When descr i bi ng the exampl es we avoi ded one-by-one steps i nvol ved i n cr eati ng the servl et because ther e i s a book dedi cated to that topi c. Pl ease refer to VisualAgefor J ava EnterpriseVersion 2: Data Access Beans - Servlets - CI CS Connector, SG24-5265, for detai l s about vi sual ser vl et constr ucti on. Sample Data Access Beans I n thi s sampl e the ser vl et takes a depar tment number, and usi ng a Sel ect bean, i t executes a quer y agai nst the empl oyee tabl e and returns the l i st of empl oyees i nto a l i st box. I t al so di spl ays the number of empl oyees wi thi n the department. For detai l ed i nfor mati on on the database tabl es str uctur e, pl ease r efer to Rel ati onal Database I nstal l ati on and Setup on page 21. Ever y database system has i ts own ser vl et cl ass and Sel ect bean. The servl et contai ns basi c i nfor mati on on the par ameters of the ser vl et, such as the department number entry fi el d. The Sel ect bean contai ns al l of the i nfor mati on on the type of database, DB2, Or acl e, or SQL Ser ver, the tabl es i nvol ved, and the type of the query. No l i ne of code i s wr i tten to cr eate thi s servl et. Al l of the code i s gener ated by Vi sual Age for Java. Al l of the i nfor mati on on the tabl es and the beans i s stored thr ough a sequence of panel s and di al ogs, as par t of the vi sual composi ti on. Creating a Servlet Visually using Data Access Beans To cr eate a ser vl et vi sual l y usi ng data access beans, we create the vi sual servl et, tai l or a Sel ect bean for database access, and then constr uct the l ogi c thr ough connecti ons i n the vi sual composi ti on. Visual Servlet To cr eate the vi sual ser vl et fol l ow these steps: Create the new ser vl et cl ass UdbDabServlet i n the itso.wasdb.accessbean package usi ng Quick Start from the menu (F2). Use the servl et pal ette i n the vi sual composi ti on edi tor to desi gn the HTML output page of the servl et. I n our exampl e we use the same HTML page for i nput and output (Fi gure 67). Chapter 8. Data Access Beans: VisualAge for Java 87 Figure67. Servlet User I nterface Noti ce the nami ng of these beans: The Html Entr yFi el d i s named deptnum The Html Text ...deptnum... i s named deptresult The Html Text ...number...i s named numemp The Retr i eve push button i s named retrieveButton Save the servl et. Thi s gener ates the underl yi ng Java code. I n parti cul ar thi s creates a JavaBean (UdbDabServletFormData) that hol ds al l the data of the data entry form, that i s, the depar tment number (deptnum) and the Retrievepush button. Fr om the Servlet pal ette (Fi gur e 68) sel ect the FormData bean and choose the UdbDabServletFormData as the cl ass name i n the di al og. Thi s cl ass was generated i n the step before. Pl ace i t somewhere outsi de the user i nter face of the ser vl et. Thi s bean represents the actual data i nput whi ch can be done i n the user i nterface. I n our exampl e, thi s bean contai ns as a property named deptnumthe depar tment val ue entered i n the Html EntryFi el d. HtmlText HtmlForm HtmlButton HtmlTable HtmlResultTable HtmlForm HtmlEntryField (deptnum) 88 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure68. TheServlet Palette Fr om the Databasepal ette dr ag and drop a Select bean and name i t UdbEmpI nDept (Fi gure 69). Figure69. Servlet with Data Access Bean and Select Bean Select Bean To tai l or the database access you open the Sel ect bean to speci fy the database connecti on and SQL statement. Doubl e cl i ck on the UdbEmpI nDept bean. Sel ect the query fi el d and cl i ck on the gr ey box. Now you can set up a database connecti on and an SQL statement (Fi gure 70). Chapter 8. Data Access Beans: VisualAge for Java 89 Figure70. UdbEmpI nDept Connection Setup Cl i ck on the New button to cr eate a new database access cl ass (UdbDabAccess) that wi l l hol d the connecti on i nformati on and the SQL statement to be executed. Cl i ck on the Add button to add a connecti on to a database (Fi gure 71). Speci fy the URL, the dr i ver, the user I D, and the password. The name of the connecti on (connect) then becomes a method name i n the database access cl ass. By defi ni ng mul ti pl e connecti ons i t i s possi bl e to access di fferent databases, or the same database wi th di fferent user I Ds (and di ffer ent ri ghts) just by choosi ng another connecti on method. 90 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure71. Connection Alias Setup Test the connecti on (the DBMS must be up and runni ng) and onl y pr oceed i f you get a successful answer. Cl i ck OK to gener ate the connect method i nto the database access cl ass. Sel ect the SQL tab to set up an SQL query (Fi gur e 72). Figure72. UdbEmpI nDept SQL Setup Chapter 8. Data Access Beans: VisualAge for Java 91 Cl i ck on the Add button and i nput the SQL Namei n the SQL Speci fi cati on panel (Fi gur e 73). Thi s name becomes the name of the method that i s generated i nto the database access cl ass. Figure73. CreatingNew SQL Specification I n most cases, you wi l l sel ect the UseSQL Assist SmartGuideradi o button. The SQL Assi st Smar tGui de enabl es you to bui l d an SQL statement wi thout much knowl edge of SQL. You go thr ough a set of pages to speci fy the tabl es, col umns, and condi ti ons of your SQL access. On the Tables page sel ect the tabl e(s) (Fi gure 74). Figure74. Selecting a Tablefor theQuery 92 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server On the Condition 1 page you can cr eate a WHERE cl ause wi th col umn speci fi cati ons. To pass a var i abl e as a val ue enter the name of a host var i abl e (:DEPTNUM ) that wi l l be set at executi on ti me (Fi gur e 75). You wi l l r ecogni ze that i f you enter a host var i abl e begi nni ng wi th a col on the name i s pri nted i n upper case bol d l etter s. Figure75. SettingQuery Condition(s) On the Columns page sel ect the col umns to be retr i eved (Fi gur e 76). Chapter 8. Data Access Beans: VisualAge for Java 93 Figure76. Selecting Columns toI ncludefor a Query On the Sort page opti onal l y sel ect the col umns used to sor t the resul ti ng rows. Thi s creates an ORDER BY cl ause i n the SQL statement. On the Mapping page you can perfor m si mpl e conver si ons of SQL data types for your Java pr ogram, for exampl e, conver ti ng numeri c data to appropri ate Java data types. The SQL page di spl ays the r esul ti ng quer y statement fr om the choi ces made i n pr evi ous pages (Fi gur e 77). 94 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure77. SQL Query Statement You can test the SQL statement by cl i cki ng on the Run SQL button. You are prompted for the host var i abl e val ue, the SQL statement i s executed, and the resul ts ar e di spl ayed i n a tabl e. Cl i ck on Finish to generate the code. The SQL statement i s added to the quer y (Fi gure 78). Chapter 8. Data Access Beans: VisualAge for Java 95 Figure78. Resulting SQL Query Up to thi s poi nt, the setup for the ser vl et and the Select bean have been descr i bed. DBMS Selection Thi s exampl e was devel oped usi ng the DB2 DBMS. To devel op a servl et that uses another database, the same steps appl y, except for the connecti on parameter s. A di ffer ent connecti on al i as, appropri ate for that database system, has to be pr ovi ded (Fi gure 71 on page 90). We devel oped the same sampl e al so for Or acl e (OrclDabServlet) and SQL Server (SqlSrvDabServlet). Logic Connections Fi gur e 79 shows the fi nal ser vl et after al l the proper connecti ons have been establ i shed between the objects and the user i nterface. Fol l ow these steps to cr eate the connecti ons: 1. Connect the retrieveButtonPressed event of the UdbDabServletFormData bean to the executemethod of the UdbEmpI nData bean. 96 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server 2. Connect the deptnumString pr oper ty of UdbDabServletFormData1 to the Parm_DEPTNUM_Stringpr oper ty of UdbEmpI nDept. 3. Connect the deptnumString pr oper ty of UdbDabServletFormData1 to the string property of the ...deptnum... Html Text bean. 4. Connect the this property of the UdbEmpI nDept Sel ect bean to the tableModel pr oper ty of the Html Resul tTabl e. 5. Connect the executed event of the UdbEmpI nDept to the stringproperty of the ...number... Html Text. The r esul t l i ne i s sti l l dashed, meani ng that a parameter i s mi ssi ng. 6. Connect the valueparameter of the pr evi ous connecti on to the numRows property of UdbEmpI nDept. Figure79. UDB Servlet Using Data Access Beans: Visual Composition At thi s poi nt you can generate the code and run i t. Tailoring the Output Result Table By defaul t the HTMLResultTablebean di spl ays the l ong col umns names, whi ch, dependi ng on the database, consi st of the schema name, the tabl e name, and the col umn name. We modi fi ed the empindept method of the UdbDabAccess cl ass to speci fy shor t col umn names (Fi gure 80). 1 2 3 4 5 6 Chapter 8. Data Access Beans: VisualAge for Java 97 Figure80. Tailored Method with Short Columns Names Running the Servlet Fi gur e 81 shows the resul t of the ser vl et i n a Web browser. Star t the WebSphere Test Envi ronment (SERunner cl ass), then enter the URL: http://127.0.0.1:8080/servlet/itso.wasdb.accessbean.UdbDabServlet Figure81. Output Result of theServlet 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); 98 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Using the Connection Manager and Data Access Beans I n thi s secti on we devel op an exampl e ser vl et that uses both the connecti on manager to establ i sh and manage the connecti ons to the database system and a non-vi sual data access bean. The servl et functi on i s to sear ch for a recor d i n the empl oyee tabl e, and di spl ay and update the record. Class Definition The fi r st step i s the cl ass defi ni ti on i n a new itso.wasdb.connaccess package (Fi gure 82). We coded the database access for al l three DBMSs, however, two are i n comments. Figure82. 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; Chapter 8. Data Access Beans: VisualAge for Java 99 The cl ass decl ar ati on has nothi ng real l y fancy i n i t. As most servl ets i t i s deri ved from HttpServlet, i t defi nes the connecti on parameter s, the user I D and the password. Thi s can be easi l y changed, or even better, the ser vl et mi ght read thi s from a pr operty fi l e. I n the l ast l i ne a StatementMetaData Object i s decl ared. Thi s object wi l l contai n al l i nformati on for the query and i n the same tur n al so for the update of the database. Initialization The next part i s the init method. The mai n pur pose of thi s method i s to i ni ti al i ze the connecti on manager and to create the StatementMetaData object (Fi gur e 83). Figure83. 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 file connSpec = new IBMJdbcConnSpec(POOLNAME, true, DRIVERNAME, URL, USER, PASSWORD); // Now get the static instance of the Connection Manager // from the Utility Class if not already done if (connMgr == null) connMgr = IBMConnMgrUtil.getIBMConnMgr(); // Next step is to prepare the Statement which will be run // agains the database. Therfor create the MetaData Object metaData = new StatementMetaData(); // Spefify the select statement for the metaData's SQL statment metaData.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 way metaData.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 query metaData.addTable("ITSO.EMPLOYEE"); } catch (DataException e) { System.out.println("Error: " + e.toString()); throw new ServletException(e.toString()); } } 100 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server I n the fi rst par t a new database connecti on i s speci fi ed. The connecti on consi sts of the constants we saw al ready i n Fi gur e 82. Afterwards a new stati c reference to the connecti on manager i s cr eated, i f not al ready ther e. I n the second par t a new StatementMetaData object i s cr eated. The SQL sel ect statement (see Fi gur e 82) i s then passed to thi s object. Noti ce the l ast part of the SELECT statement: ".... WHERE LASTNAME = :LNAME" Thi s var i abl e LNAME wi l l be l ater r epl aced by an actual val ue. To do thi s, LNAME has to be speci fi ed as an i nput par ameter, whi ch i s done i n the next l i ne. Mor eover, i t al so speci fi es the Java cl ass that wi l l be used to speci fy thi s parameter, and what the resul ti ng SQL type i s. I f you observe any pr obl ems her e refer to Data Access Beans on page 266. The next l i nes ar e qui te si mi l ar except that now the output col umns ar e speci fi ed. The ar guments are the SQL col umn name, the Java cl ass that i s used to r epresent thi s val ue, and the accor di ng SQL type. We wi l l see l ater that i t i s useful to provi de thi s i nformati on to al l ow a conveni ent access to the resul t set and, mor eover, i t i s a ni ce way to update a row. The l ast l i ne speci fi es the SQL tabl e that contai ns al l the gi ven col umns. Form Parameter Access The getParameter method i s a hel per method (Fi gur e 84). Figure84. EmployeeServlet getParameter Method Thi s method i s handy to r etri eve the par ameter gi ven to a servl et i n the request. I t just r eturns the fi r st val ue for a key fr om the request object gi ven to the servl et. For exampl e, i f the HTTP request i s: http://myserver/Servlet?firstName=Tobias&lastName=Himstedt&firstName=Amir then getParameter(request, "firstName") woul d r etur n "Tobias". public String getParameter(HttpServletRequest request, String key) { String values[] = request.getParameterValues(key); if (values != null) return values[0]; return null; } Chapter 8. Data Access Beans: VisualAge for Java 101 Form Processing The next thi ng to i s to defi ne doGet and doPost. Because they shoul d do the same, we cal l the same performTask method so that we ar e fr ee to use ei ther HTTP-POST or HTTP-GET. The ser vl et works wi th both opti ons (Fi gur e 85). Figure85. EmployeeServlet doGet and doPost Methods Both methods cal l the performTask method, whi ch i tsel f i s al so ver y si mpl e. Dependi ng on the r equest, i t ei ther cal l s the method to r etri eve the data for an empl oyee or to update the data (Fi gure 86). Figure86. EmployeeServlet performTask Method Based on the val ue for the command parameter i n the HttpServletRequest object, per formTask ei ther cal l s getEmployeeto fetch a speci fi c r ow fr om the empl oyee tabl e or updateEmployeeto update an al ready fetched r ow. 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); } 102 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Employee Retrieval The getEmployeemethod processes the retr i eval of an empl oyee (Fi gure 87). Figure87. EmployeeServlet getEmployeeMethod (I ) What i s happeni ng so far i s not ver y exci ti ng. Basi cal l y, the r esponse i s speci fi ed, the cachi ng i s di sabl ed, the output PrintWriter i s cr eated fr om the response object, and the par ameter for the database query i s detected. Next the begi nni ng of the resul t page i s pri nted to the PrintWriter. The next part r etri eves a connecti on to the database based on the speci fi cati on made i n the i ni t method (see Fi gure 83) fr om the connecti on manager. Fr om thi s connecti on a JDBC connecti on i s created. Thi s i s used to cr eate a DatabaseConnection used for the data access beans (Fi gure 88). Figure88. EmployeeServlet getEmployeeMethod (I I ) The next part i s about how to use the DatabaseConnection object to cr eate a SelectStatement based on the SelectMetaData i ni ti al i zed i n the init method (Fi gure 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 writer PrintWriter out = response.getWriter(); // Get the lastName paramenter for query String queryName = getParameter(request, "lastName"); out.println("<HTML><HEAD><TITLE>ConnMgr / DataAccess</TITLE></HEAD><BODY>"); try { // Get the connection from the connection managers pool conn = (IBMJdbcConn) connMgr.getIBMConnection(connSpec); // Get the JDBC connection object jdbcConn = conn.getJdbcConnection(); // Now use this JDBC connection for the creating // a connection usable by the data access beans DatabaseConnection dataConnection = new DatabaseConnection(jdbcConn); Chapter 8. Data Access Beans: VisualAge for Java 103 To execute the quer y agai nst the database the quer y has to be compl eted wi th the actual quer y val ue. The val ue i s r etri eved from the servl et r equest (Fi gure 87 on page 102) and i s then passed as parameter LNAME to the quer y. Now the quer y i s ready to execute. After executi on the resultSet i s retr i eved. Figure89. getEmployeeMethod (I I I ) I n Fi gur e 90 the val ues for the col umns are retr i eved. Based on the col umn val ues the HTML output i s generated as a tabl e wi th a form i n i t. Thi s enabl es the user to enter val ues for al l the fi el ds except for the pri mary key. Figure90. EmployeeServlet getEmployeeMethod (I V) 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>"); 104 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Noti ce the acti on attr i bute of the FORM tag. I t poi nts back to the same servl et. I n the source code thi s mi ght l ook a bi t wi l d, but as HTML output i n the browser, i t i s strai ghtfor war d and i s shown i n Fi gure 91. Figure91. Output of thegetEmployeeMethod Conti nui ng wi th the ser vl et code we have one more i mpor tant thi ng to do. We stor e the resultSet i n a sessi on object associ ated wi th the servl et r equest. Thi s enabl es us l ater to use thi s resultSet to update the row (Fi gur e 92). Figure92. EmployeeServlet getEmployeeMethod (V) The l ast part contai ns the er ror handl i ng statements (Fi gur e 93). Figure93. EmployeeServlet getEmployeeMethod (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>"); } Chapter 8. Data Access Beans: VisualAge for Java 105 Employee Update After retr i evi ng an empl oyee, the user can update the col umn val ues. The updateEmployeemethod per for ms the processi ng. The method begi ns wi th some admi ni strati ve code (Fi gur e 94). Figure94. EmployeeServlet updateEmployeeMethod (I ) I n Fi gure 95 the sessi on we created (see Fi gure 92) i s now r etri eved from the servl et r equest. I n thi s sessi on we have stor ed the resultSet of the query. Figure95. EmployeeServlet updateEmployeeMethod (I I ) Next we r etri eve the val ues from the i nput fi el ds (Fi gur e 96). Figure96. EmployeeServlet updateEmployeeMethod (I I I ) Now we ar e r eady to perfor m the update (Fi gur e 97). I f the val ues wer e gi ven, they are passed to the resultSet of the query r etri eved by the getEmployeeMethod. Fi nal l y the r ow i s updated and cl osed; al so the connecti on manager i s i nformed that the connecti on i s rel eased. 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 writer PrintWriter 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"); 106 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure97. EmployeeServlet updateEmployeeMethod (I V) The l ast part contai ns the er ror handl i ng statements (Fi gur e 98). Figure98. EmployeeServlet updateEmployeeMethod (I V) Testing the Servlet To test the servl et you may want to use to WebSpher e Test Envi ronment provi ded by Vi sual Age for Java (star t the SERunner cl ass). Open a browser and enter the URL: http://127.0.0.1:8080/servlet/itso.wasdb.connaccess.EmployeeServlet?lastName=LEE Al ternati vel y you can l aunch the ser vl et fr om Vi sual Age for Java. Before l aunchi ng the ser vl et, you can setup the query par ameter (host vari abl e) i n the servl et pr oper ti es so that an empl oyee i s found i n the tabl e. Fr om the context menu of EmployeeServlet sel ect Tools ->Servlet Launcher ->Properties to di spl ay the ser vl et l auncher pr oper ti es di al og and enter the val ues shown i n Fi gure 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>"); } Chapter 8. Data Access Beans: VisualAge for Java 107 Figure99. Properties for theEmployeeServlet After l aunchi ng the ser vl et the browser shoul d appear as shown i n Fi gur e 91 on page 104. You may then enter the text fi el ds to update the database. I f the update was successful , the ser vl et wi l l l et you know wi th a message. Deploying Servlets to WebSphere For detai l ed i nstructi ons on depl oyi ng ser vl ets to WebSpher e, see chapter 20 of the I BM redbook VisualAgefor J ava EnterpriseVersion 2: Persistence Builder with GUI s, Servlets, and J ava Servlet Pages, SG24-5426. An exampl e of depl oyment of a ser vl et to WebSphere i s descr i bed i n Depl oyi ng a Servl et to WebSphere on page 128. Make sur e that the c:\IBMVJava\eab\runtime20\ivjdab.jar fi l e i s part of the WebSpher e cl ass path. 108 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 109 9 Persistence Builder: VisualAge for Java I n thi s chapter we di scuss the use of rel ati onal databases to provi de persi stence for Java objects. We wi l l use the Vi sual Age for Java Per si stence Bui l der tool to create persi stent cl asses based upon exi sti ng database tabl es. We wi l l use our I TSOWDB database as descri bed i n Chapter 4, Rel ati onal Database I nstal l ati on and Setup on page 21. For these exampl es, the Per si stence Bui l der tool must be added to your workspace. You can add the feature from File->Quick Start ->Features -> Add Feature->EnterpriseAccess Builder for Persistence. I f you have al ready added the WebSphere Test Envi r onment feature, the Persi stence Bui l der featur e wi l l r epor t an er ror when the feature i s added. As the err or message i ndi cates you must remove the Webspher e Test envi ronment feature, then add the Enter pri se Access Bui l der for Persi stence feature agai n. Thi s wi l l al so i nstal l the WebSpher e Test Envi ronment for you. Notice 110 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server What is Persistence? I n Java, as wi th al l programmi ng l anguages, the state of an object i s l ost when the object fi ni shes executi on, unl ess the state of the object i s external i zed befor e executi on i s compl ete. Thi s i s tr ue for any i nfor mati on whi ch a progr am uti l i zes. I n Java, savi ng the state, or any i nformati on, befor e pr ogram compl eti on and restor i ng the state, or retr i evi ng i nformati on, when the object i s i nstanti ated agai n, i s known as persistence. Java per si stence can be achi eved by serializing an object. That means converti ng the objects state i nto a sequence of bytes, then stor i ng the bytes, whi ch can l ater be read to r esur rect the or i gi nal object. Thi s way an object does not need to know how to access a fi l e to r etri eve data i tsel f; i nstead, whoever cal l s the object resurr ects the enti re object, i ncl udi ng any data and the object state. Using Databases to Provide Persistence Databases can al so be used to provi de persi stence for Java objects. The objects state can be stored i n a tradi ti onal SQL database and then resurr ected by queryi ng the database. The Persi stence Bui l der i s a Vi sual Age for Java tool whi ch gui des you through the cr eati on of cl asses that pr ovi de persi stence functi onal i ty. Al though the tool can be used to create per si stent objects from scratch, one of Persi stence Bui l ders most powerful abi l i ti es i s to take an exi sti ng database and cr eate a persi stent Java appl i cati on usi ng the exi sti ng desi gn of that database. The tool i ncl udes al l of the r el ati ons between tabl es and database rul es i n i ts desi gn. I t cr eates object defi ni ti ons based on your tabl es, whi ch can be used i n your Java appl i cati ons. Persistence Builder Tools For detai l ed i nstructi ons on usi ng the Persi stence Bui l der, r evi ew the redbook VisualAgefor J ava Enterprise2: PersistenceBuilder with GUI s, Servlets, and J ava Server Pages, SG24-5426. The tool has thr ee major components used to defi ne how the tool wi l l create your Java code for i mpl ementi ng object persi stence. The Schema, Model, and Mapping Br owsers enabl e you to defi ne the tabl e model , the object model , and the mappi ng between the two model s. Chapter 9. Persistence Builder: VisualAge for Java 111 Schema Browser The Schema Browser i s used to i mpor t, create, vi ew, and modi fy the rel ati onshi ps between the actual tabl es i n your database. Thi s browser i s wher e the Per si stence Bui l der gathers the necessar y i nformati on (for exampl e, col umn defi ni ti ons, forei gn key rel ati onshi ps) fr om your database to cr eate objects based on the data stor ed wi thi n. Usi ng your newl y cr eated schema, a model can be generated based on the schema. Model Browser The Model Br owser cr eates the actual persi stent cl asses whose data wi l l be external i zed. I t adds to these objects attri butes and associ ati ons from the schema. I t i s i mpor tant that the schema trul y repr esents your physi cal database to ensure that the objects can i nter act cor rectl y wi th the actual database. I n our exampl e the objects wi l l be empl oyee and department. Map Browser The Map Br owser i s used to control mappi ngs between the tabl es and the model cl asses. I t i s used to map the object attr i butes and associ ati ons to the actual database tabl es. Vendor Specific Considerations As thi s book was wr i tten, the rel eased ver si on of Vi sual Age for Java Persi stence Bui l der onl y suppor ted the i mporti ng of DB2 databases to cr eate a per si stent appl i cati ons schema. A fi x for i mpor ti ng Oracl e and SQL Ser ver databases to create a schema was wr i tten as thi s book went to publ i shi ng. The fi x requi res a package to be i mported and a fi l e to be pl aced i n your Vi sual Age for Java di rectory. Wi th thi s fi x, you can i mport the Or acl e or SQL Server database and cr eate the proper schema. I f your ver si on of Vi sual Age for Java fai l s to i mport these schemas, contact Vi sual Age for Java suppor t for the pr oper fi xes. 112 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Persistence Builder Example: Employees in Department We wi l l attempt to take an exi sti ng database from DB2, Oracl e, and SQL Server to create a si mpl e per si stent object model . Then we wi l l cr eate a servl et that uses thi s model . The ser vl et takes a depar tment number as i nput and returns a l i st of empl oyees wi thi n that depar tment. The fi r st step i s to cr eate a schema for your objects based on your tabl e. Import the Schema Fr om your Workbench, open the Schema Br owser by sel ecti ng Workspace-> Tools ->PersistenceBuilder Tools ->BrowseSchema. Si nce we want to cr eate our schema fr om an exi sti ng database, we use the i mpor t functi on. Thi s type of desi gn i s al so known as a bottom-up desi gn because we are starti ng wi th a database and bui l di ng our appl i cati on ar ound i t. Sel ect Schema ->I mport / Export Schema ->I mport Schema fromDatabase. Now enter the name you wi sh to cal l your schema; i n our exampl e, we cal l the schema I TSO. You must now enter the JDBC connecti on i nfor mati on (Fi gur e 100). Thi s connecti on i nfor mati on i s dependent on the database vendor you are usi ng as a datastore. The connecti on and dri ver speci fi cati ons used here shoul d r el ate to the i nformati on used to create a connecti on i n Chapter 5, J ava Database Connectivity on page43. Figure100. I mportinga Schema Chapter 9. Persistence Builder: VisualAge for Java 113 Once the connecti on i s establ i shed, you sel ect the tabl es you want to i mpor t from. Each tabl e you want to i mpor t must be hi ghl i ghted (use the shi ft key wi th the mouse for mul ti pl e sel ecti ons) as i n Fi gure 101. Figure101. I mport TableSelection The Per si stence Bui l der now gener ates the schema fr om the database and di spl ays i t i n the Schema Browser (Fi gure 102). The schema i s a representati on of your actual database. You shoul d l ook at each col umns attr i bute by doubl e cl i cki ng on the attr i bute and confi rm that i t i s the cor rect type (Fi gur e 103). I t i s al so a good i dea to i nspect the for ei gn key rel ati onshi ps. I t i s i mportant that al l for ei gn keys fr om the tabl e are di spl ayed i n the schema. I f a rel ati onshi p i s not shown, cr eate one based on the physi cal tabl e i n the database, other wi se the cor rect cl asses wi l l not be created l ater on. We renamed the forei gn key rel ati onshi p to depts (Fi gure 102). When the schema i s generated from your database, i f the forei gn key r el ati onshi p i s not gi ven a name i n your SQL statements, the schema browser uses the i nter nal restrai nt name used by your database. To rename a rel ati onshi p, use the rel ati onshi ps context menu and sel ect RenameForeign Key Relationship. 114 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure102. Schema Browser Figure103. Schema Column Editor Chapter 9. Persistence Builder: VisualAge for Java 115 Generate and Validate the Object Model The next step i s to generate the model fr om the schema. Sel ect Schemas -> GenerateModel fromSchema. The Per si stence Bui l der bui l ds a model of the objects based on the database schema. You shoul d now open the Model Browser. You can open i t ei ther from the tool s menu from the Workbench as descr i bed earl i er, or from the schema wi ndow, sel ect PersistenceBuilder Tools ->Model Browser. The Model Br owser (Fi gur e 104) i s a vi ew of the object model ; i nstead of tabl es and col umns i t has cl asses and attr i butes. Figure104. Model Browser Not al l of the col umn speci fi cati on from the schema tr ansfers to the object model . I t i s i mpor tant to i nspect the cl asses, attri butes, and keys as wel l . Noti ce that the NOTNULL opti on of col umns i n the tabl es does not cause the Valuerequired checkbox to be mar ked. You shoul d open al l of the attr i butes that map to col umns that are not nul l (by doubl e cl i cki ng on the cl ass attr i bute to edi t) and checki ng the Valuerequired checkbox (Fi gure 105). 116 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure105. AttributeEditor: Marking theValueRequired Field Inspect the Map Open the Map Browser (under Per si stence Tool s) to i nspect the mappi ng from the schema to the model . I f the model objects do not map pr oper l y to the physi cal database, the map br owser wi l l i nform you. The map was cr eated when you gener ated the model fr om the schema. I t i s i mpor tant that the mappi ng i s corr ect befor e you attempt to generate the Java code, or some of the gener ated Java methods wi l l not functi on pr oper l y. I n the Map Br owser sel ect the generated DataStore Map, i n thi s exampl e I TSOI tso. I n Fi gur e 106 we see a br oken tabl e mappi ng. I n thi s parti cul ar exampl e we see an er ror conver ti ng the type of the tabl e col umn to the cl ass attr i bute. I f you open the tabl e i n the Schema Br owser, we see that Empl oyee.hi redate has a type TI MESTAMP. I f you then l ook i n the Model Br owser, the hi r edate attr i bute has a type DATE. Chapter 9. Persistence Builder: VisualAge for Java 117 Figure106. Map Browser with a Broken TableMap We have two ways of fi xi ng thi s mappi ng pr obl em: we can change the mappi ng functi on by doubl e cl i cki ng on the attri bute i n err or, or change the type of one of the attr i butes i n confl i ct. We chose to change the type of the hiredateattr i bute i n the Model Br owser to a type of java.sql.Timestamp. The err or di spl ayed i n the Map Br owser i s then cl ear ed as i n Fi gur e 107. Figure107. Model Browser I f you have found any err ors or made any changes i n the Schema Browser, remember to regener ate the model based on the new schema. 118 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Generate the Java Code for the Object Model Now that the three browser s cor rectl y defi ne how you want your objects to behave, i t i s ti me to gener ate the actual code. Fr om your Model Browser, sel ect Models ->Generate. Three opti ons are presented i n the SmartGui de (Fi gure 108). Figure108. Generation Options The fi r st step i s to generate the Java cl asses and i nter faces of the object model , whi ch i s the fi rst r adi o button. The next panel prompts you for the project and package names. For our exampl e, we used the itso.wasdb.persist package. As shown i n Fi gur e 109, you shoul d mark the GenerateBound Beans Properties checkbox. Model cl asses wi th bound proper ti es fi r e propertyChange events, whi ch i s useful when creati ng appl i cati ons usi ng vi sual constr ucti on. Chapter 9. Persistence Builder: VisualAge for Java 119 Figure109. Generation Options (Bean Properties) The next panel asks you whi ch model el ements you woul d l i ke to gener ate; for our exampl e, al l of the el ements. Cl i ck on the Finish button and the cl asses are generated. Generate the Java Code for the Service Classes Now that the object cl asses have been defi ned, i t i s necessar y to generate the servi ce cl asses that wi l l handl e the persi stent aspect of your objects. The servi ce cl asses are responsi bl e for external i zi ng al l of the i nfor mati on i n your objects and l ater resurr ecti ng those objects. Fr om the Model Browser, sel ect Models ->Generate. Thi s ti me you wi l l sel ect the second r adi o button di spl ayed i n Fi gur e 108 on page 118, Data Service Classes and I nterfaces. The next panel prompts you for the type of schema to gener ate. We ar e usi ng the exi sti ng rel ati onal database to stor e the i nfor mati on, therefore we sel ect the thi rd radi o button, Relational SQL 120 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server (Fi gure 110). Enter the package name for the servi ce cl asses, i n our case itso.wasdb.persist.Services. Figure110. Schema Generation Selection After compl eti ng thi s panel , sel ect Next to di spl ay the database connecti on i nfor mati on prompt. Enter the corr ect i nformati on to connect to the database (same as i n Fi gure 100 on page 112) and then sel ect the Generatequeries using parmmarker bindings checkbox (Fi gur e 111). Chapter 9. Persistence Builder: VisualAge for Java 121 Figure111. DatabaseConnection I nformation Next you wi l l be prompted for the model el ements to i ncl ude, i n our case al l el ements and then cl i ck on Finish. I f you l ook i n the Wor kbench, you wi l l see that your packages have been successful l y cr eated. You ar e now r eady to bui l d a persi stent appl i cati on, but fi r st, save the model , schema, and map defi ni ti ons i n the itso.wasdb.persist.metadata package (use the Filemenu i n each browser). Build the Servlet Now that al l the cl asses are i n pl ace, you can cr eate a vi sual ser vl et to i nter act wi th the persi stent objects. Fr om the Workbench, sel ect File->Quick Start ->Servlets ->Visual Servlet. You ar e pr ompted for the pr oject, package, and name of ser vl et. Use a nami ng conventi on you feel comfortabl e wi th. We used the itso.wasdb.persist.gui package and we named the servl et EmpsI nDept and sel ected a si mpl e model to wor k wi th. 122 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The next panel asks you the name of the servl et to use for the Acti on form; we used the same ser vl et name. Cl i ck on Finish and the Smar tGui de cr eates the cl asses and opens the vi sual composi ti on edi tor. We wi l l not go i nto depth concerni ng the use of the vi sual composi ti on edi tor, i nstead we di spl ay some of the steps and the r esul ti ng desi gn. Visual Layout of the HTML Output Page We fi rst have to cr eate the HTML output page i tsel f. I n Fi gur e 112, we have cr eated the form to enter the department name. There are a few Html Text beans, an Html EntryFi el d that we named DeptEntryField, and a Html PushButton named DeptSubmitButton. The prompt, entry fi el d, and button are wi thi n a thr ee col umn, si ngl e r ow tabl e. At the bottom we use another for m wi th an Html Resul tTabl e named EmpListResult. Save the desi gn so that the FormData bean i s gener ated. The composi ti on of the ser vl et i s ver y si mi l ar to the one gi ven i n Creati ng a Servl et Vi sual l y usi ng Data Access Beans on page 86. Figure112. HTML Output Pageof a Servlet Chapter 9. Persistence Builder: VisualAge for Java 123 Beans for Data Retrieval Next we pl aced the beans requi red for the l ogi c. We sel ect the FormData bean from the pal ette and sel ect the EmpsI nDeptFomdata that was generated when savi ng the vi sual l ayout. Thi s bean r epresents the HTML for m and has al l the i nfor mati on and acti ons that can take pl ace on the vi sual for m. Because we ar e enteri ng a depar tment number, we have to retr i eve the actual department object for that number. I f we want to fi nd al l empl oyees i n a depar tment, we star t wi th the department object and fol l ow the rel ati onshi p to get the empl oyees. To retr i eve the department object we use a and enter the DeptHomeBean cl ass from the itso.wasdb.persist package. Once that department object i s found, i t needs a pl ace to be stored, therefore we pl ace a depar tment object on the page as wel l . We use a tr ansacted var i abl e of type DepartmentHomeI mpl to r epresent the depar tment retr i eved thr ough the home cl ass. We now swi tch to the Persi stence Bui l der pal ette to add the objects we wi l l need to enact the persi stence ser vi ces. We sel ect a read-onl y tr ansacti on bean because we ar e onl y readi ng i nformati on wi thout any updates. We al so use a VapDefaultRelationshipTableModel bean to conver t the l i st of empl oyees i nto a di spl ayabl e for m. Both of these i cons are i n the pal ette (Fi gure 113). Figure113. Visual Composition Editor with PersistenceBuilder Palette 124 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Connections for the Logic Now that we have al l the necessar y beans, we must add the connecti ons between the objects (Fi gure 114). Figure114. Composition Editor with Connections Connecti ons: 1. Retri eve the department when the for m i s submi tted: EmpsI nDeptFor mData(Event DeptSubmitButtonPressed) to Depar tmentHome(find(java.lang.String) method) 2. Pass the depar tment number enter ed to the fi nd method: EmpsI nDeptfor mData(property deptEntryFieldString) to par ameter of fi nd(deptno) 3. Stor e the resul t of the fi nd method as a depar tment object: NormalResult to Depar tmentHomeI mpl (this) 4. Set the curr ent transacti on for the department: ReadOnl yTransacti on(this) to Depar tmentHomeI mpl (transaction) 5. Set the curr ent transacti on for the empl oyee r esul t: ReadOnl yTransacti on(this) to VapDefaul tRel ati onshi pTabl eModel (transaction) 6. Retri eve the empl oyees of the department: Depar tmentHomeI mpl (pr oper ty employee) to VapDefaul tRel ati onshi pTabl eModel (relationship) 6 4 5 7 2 1 3 Chapter 9. Persistence Builder: VisualAge for Java 125 7. Di spl ay the empl oyees of the department: VapDefaul tRel ati onshi pTabl eModel (this) to EmpLi stResul tTabl e(tableModel) Tailor the Result Table After al l of the connecti ons ar e establ i shed, the properti es of the VapDefaultRelationshipTableModel have to be set. The bean needs to know whi ch col umns of data you want to di spl ay i n the r esul t tabl e. Doubl e cl i ck on the object to access i ts proper ti es, then al ter the columnI dentifiers r ow (cl i ck on the l i ttl e push button that appears i n the r ow). Fi gur e 115 shows the di al og used to set the object cl ass and the pr oper ti es (col umns of the tabl e) that we want to show i n the output. Figure115. Column I dentifiers You must enter the ful l name of the cl ass (itso.wasdb.persist.Employee) and then i ts properti es ar e di spl ayed automati cal l y i n the mi ddl e pane. Sel ect the desi red properti es and cl i ck on Add to set the col umns of the resul t tabl e. 126 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Test the Servlet Once you have compl eted al l of these steps, your ser vl et shoul d be ready to run. Press Ctr l -S to save your wor k and then cl i ck on the Run i con on the tool bar. Thi s star ts the WebSphere Test Envi ronment (servl et r unner ) and di spl ays the HTML page wi th the defaul t br owser (Fi gur e 116). Figure116. Servlet Test Output The ser vl et does not acti vate the datastor e you have created wi th the Persi stence Bui l der tool . For the servl et to work, you must acti vate the datastor e befor e doi ng any processi ng. The best pl ace to add the datastor e acti vati on i s the initializemethod of the ser vl et: itso.wasdb.persist.Services.ITSOItsoDataStore.singleton().activate(); The si ngl eton method creates one i nstance of the datastore (i ndependent of how many ti mes i t i s cal l ed), and the acti vate method star ts the datastore. Pl ace the statement after the comment l i ne // user code begin (1). Thi s code i s pr eserved even i f the method i s r egener ated. Notice Chapter 9. Persistence Builder: VisualAge for Java 127 Changing the Datastore Database Once you have cr eated the persi stent ser vl et, i t i s possi bl e to change whi ch database manager pr oduct i s used for per si stent storage. You must dupl i cate the compl ete database i n the new database manager product. The detai l s of compl eti ng thi s task i s beyond the scope of thi s book. To change the datastor e, si mpl y regener ate the servi ces cl ass of the persi stent ser vl et fr om the Model Br owser. Thi s ti me speci fy the connecti on i nfor mati on for the new database manager pr oduct. Another way to change whi ch database pr oduct i s used as a datastor e i s to make a smal l manual change i n the datastore servi ces cl ass. The database connecti on i nformati on i s stored i n the getConnectionSpec method of the I TSOI tsoDataStorecl ass i n the itso.wasdb.persist.Services package. Thi s code control s the dri ver and connecti on i nformati on that your object uses to communi cate wi th the database. By changi ng the dr i ver and connecti on i nformati on, we can change the database product, as l ong as i denti cal tabl es exi st i n the di ffer ent database manager s. Fi gur e 117 shows the cor rect setti ngs for our exampl e to i nteract wi th DB2, Or acl e, and SQL Server. Note that thi s code i s r emoved i f you regenerate the servi ce cl asses! Figure117. EstablishingConnections toMultipleDatabaseVendors //* WARNING: THIS METHOD WILL BE REGENERATED. */ public com.ibm.ivj.db.base.DatabaseConnectionSpec getConnectionSpec() { DatabaseConnectionSpec aConnectionSpec; DatabaseConnectionSpec forDB2, forOracle, forSQLServer; // DB2 UDB app driver forDB2 = new DatabaseConnectionSpec ("VA1","COM.ibm.db2.jdbc.app.DB2Driver", "jdbc:db2:itsowdb"); // Oracle thin driver forOracle = new DatabaseConnectionSpec ("VA1","oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@localhost:1521:orcl"); // SQL Server jdbc/odbc bridge forSQLServer = new DatabaseConnectionSpec ("VA1","sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:SQLServer"); aConnectionSpec = forDB2; // aConnectionSpec = forOracle; // aConnectionSpec = forSQLServer; aConnectionSpec.setLogonSpec(new DatabaseLogonSpec ("itso", "itso")); return aConnectionSpec; } 128 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Deploying a Servlet to WebSphere Your new servl et i s r eady to r un on the WebSphere server, but you must make sure that al l the pr oper r esour ces are avai l abl e on the Web ser ver. For detai l ed i nstr ucti ons on depl oyi ng per si stent servl ets to WebSpher e, see chapter 20 of the I BM redbook VisualAgefor J ava EnterpriseVersion 2: PersistenceBuilder with GUI s, Servlets, and J ava Servlet Pages, SG24-5426. The fi r st thi ng to move to WebSphere i s the datastor e. Be sur e that the database tabl es and fi l es are avai l abl e on the WebSpher e ser ver. I t i s i mportant that the database i s i denti cal to the database used i n the test envi ronment. Next expor t al l of the servl et code and copy i t to WebSphere. I n our exampl e, we cr eated three packages whi ch must be exported (Fi gure 118). Pl ace al l of these cl asses i n the WebSphere servl et di r ectory. Figure118. Exporting theServlet Chapter 9. Persistence Builder: VisualAge for Java 129 Wi th the code moved to WebSphere, i t i s i mper ati ve that al l of the cl asses that your persi stent appl i cati on uti l i zes ar e avai l abl e i n the WebSpher e envi ronment. We do not go thr ough al l of the WebSpher e admi ni strati on pages. For now, the most i mportant setti ng to get Vi sual Age for Java ser vl ets to work i s the cl ass path setti ng, and that i s on the Setup ->J ava Enginepage (Fi gure 119). Figure119. WebSphereApplication Server: J ava EngineSetup We used the fol l owi ng cl ass path: D:\jdk1.1.6\lib\classes.zip; <=== JDK D:\WebSphere\AppServer\classes; <=== export directory D:\WebSphere\AppServer\web\classes; D:\SQLLIB\java\db2java.zip; <=== DB2 JDBC Drivers D:\orant\Jdbc\lib\classes111.zip; <=== Oracle JDBC Drivers D:\IBMVJava\eab\runtime20\ivjdab.jar; <=== data access beans D:\IBMVJava\eab\runtime20\ivjsb21.jar; <=== servlet builder D:\IBMVJava\eab\runtime20\ivjpb20.jar; <=== persistence builder D:\IBMVJava\eab\runtime20\ivjpb20e.jar; <=== pers. builder extras (see below) D:\IBMVJava\hpj\lib\swingall.jar; <=== swing 130 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server To si mpl i fy the cl ass path, we copi ed the JAR fi l es i nto the di r ectory D:\WebSphere\AppServer\lib. Jar fi l es i n the lib subdi r ectory are automati cal l y added to the WebSpher e cl ass path and do not have to be speci fi ed i n the admi ni str ati on setup. Three of these JAR fi l es ar e speci al cases: The ivjpb20e.jar fi l e i s not pr ovi ded by Vi sual Age for Java. We bui l t thi s fi l e oursel ves by expor ti ng the VisualAgePersistenceExtras pr oject from Vi sual Age for Java. Thi s i s the pr oject wi th the addi ti onal cl asses to i nter act wi th AWT and Swi ng fr om Per si stence Bui l der home and rel ati onshi p col l ecti ons. The ivjdab.jar fi l e contai ns the same cl asses as the databean.jar fi l e provi ded by WebSphere, pl us extra GUI cl asses. To make sur e that the ivjdab.jar fi l e i s l oaded before the databean.jar fi l e, we added i t to the cl ass path. The ivjpb20.jar fi l e contai ns the same cl asses as the ejs.jar fi l e provi ded by WebSphere, pl us extr a cl asses. To make sur e that the ivjpb20.jar fi l e i s l oaded before the ejs.jar fi l e, we added i t to the cl ass path. Your persi stent servl et shoul d successful l y r un i n WebSpher e wi th thi s cl ass path setti ng. Copyright IBM Corp. 1999 131 10 Enterprise JavaBeans I n thi s chapter we wi l l br i efl y di scuss what Enterpri se JavaBeans ar e and how they are used i n conjuncti on wi th WebSphere, Vi sual Age for Java, and databases. For fur ther i nformati on refer to http://java.sun.com/products/ejb/docs.html or to the r edbook Enterprise JavaBean Development with VisualAge for Java, SG24-5429. Note that Enter pri se JavaBeans i s the name of the ar chi tecture as speci fi ed by Sun; what we devel op we wi l l si mpl y cal l enter pri se beans. 132 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Enterprise JavaBeans from a Birds-Eye Perspective An Enter pri se JavaBean i s a nonvi sual component whi ch runs on the server si de of a di stri buted appl i cati on. The enter pri se bean i tsel f l i ves i n an envi ronment cal l ed an EJB contai ner. The EJB contai ner i n tur n runs i n an EJB server or Enterpr i se Java Server (EJS). The goal s of the EJB archi tectur e i ncl ude: Maki ng l i fe easi er for the devel oper: The devel oper does not have to str uggl e wi th l ow-l evel enti ti es such as per si stence, threads, and transacti ons; i n that the EJB archi tectur e enabl es the devel oper to concentr ate on the busi ness l ogi c. Maki ng server appl i cati ons por tabl e: The model ensur es that Java pl atform ser ver components can be devel oped once and depl oyed anywher e. Maki ng the server appl i cati on i ndependent: The Enterpri se JavaBeans archi tectur e i s compl etel y i ndependent from any speci fi c pl atform, protocol , or mi ddl ewar e i nfrastructure. Appl i cati ons that ar e devel oped for one pl atfor m can be pi cked up, moved, and redepl oyed to another pl atform. A Closer Look So far we have seen the abstr act term of enterpr i se bean, EJB contai ner s, and EJB servers. We wi l l now take a cl oser l ook at those ter ms. There are two types of enter pri se beans: sessi on beans and enti ty beans. Session beans can be stateful or statel ess. Stateful sessi on beans exi st for the durati on of a si ngl e cl i ent/ser ver sessi on. Statel ess sessi on beans are pool ed by the contai ner to handl e mul ti pl e requests from mul ti pl e cl i ents. Entity beans contai n per si stent data that can be saved i n var i ous persi stent data stor es. Each enti ty bean carr i es i ts own i denti ty; that means enti ty beans do have pri mar y keys. Enti ty beans that manage thei r own persi stence ar e cal l ed bean managed per si stence (BMP) enti ty beans. Enti ty beans that del egate thei r persi stence to the EJB contai ner are cal l ed contai ner managed persi stence (CMP) enti ty beans. The homeinterfacespeci fi es the avai l abl e methods for l ocati ng, creati ng, and r emovi ng i nstances of enterpr i se bean cl asses. Thi s i s nor mal l y pr ovi ded by the devel oper. Chapter 10. Enterprise JavaBeans 133 The remoteinterfacespeci fi es the busi ness methods of the enter pri se bean. Typi cal l y, the devel oper of the enter pri se bean al so defi nes the r emote i nter face. An EJ B container i s a r unti me envi r onment that manages one or more enter pr i se beans. Speci fi cal l y, contai ners manage the l i fe cycl es of enter pri se bean objects, coor di nate di stri buted tr ansacti ons, and i mpl ement object securi ty. The depl oyment descr i ptor, a seri al i zed object that contai ns run-ti me setti ngs for an enter pri se bean, tel l s the EJB contai ner how to manage and contr ol an enterpr i se bean. General l y, each EJB contai ner contai ns a set of enter pri se beans. EJB contai ners ar e typi cal l y pr ovi ded by EJB server s. An EJ B server i s a hi gh-l evel pr ocess or appl i cati on that pr ovi des a run-ti me envi ronment to suppor t the executi on of ser ver appl i cati ons that use enter pri se beans. An EJB server provi des a JNDI -accessi bl e nami ng servi ce, manages and coordi nates the al l ocati on of resources to cl i ent appl i cati ons, pr ovi des access to system resources, and pr ovi des a transacti on servi ce. An EJB server coul d be, for exampl e, a database or appl i cati on server. Developing a Container Managed Persistence Entity Bean I n thi s secti on we devel op a si mpl e enter pri se bean. Because thi s book i s about WebSphere and database i ntegr ati on, we devel op thi s enti ty bean based on the empl oyee/depar tment sampl e that we ar e usi ng throughout thi s book. For the devel opment process we uti l i ze Vi sual Age for Java. Mor eover we show how to depl oy the enterpr i se bean to use i t wi thi n WebSpher e from a servl et, and we al so show how to use thi s enter pri se bean from an appl et or appl i cati on. I n our versi on of WebSphere Appl i cati on Ser ver (Versi on 2.0.2), and al so i n the WebSphere Test Envi ronment of Vi sual Age for Java, contai ner managed per si stence (CMP) onl y wor ks wi th DB2 and not wi th Or acl e and SQL Server. Ther efor e, thi s fi r st exampl e wi l l onl y work wi th DB2. The next exampl e uses bean managed per si stence (BMP) and works wi th al l JDBC compl i ant databases. Notice 134 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Setup of VisualAge for Java Fol l ow these steps to set up Vi sual Age for Java: Make sur e you added the I BM EJ B Development Environment 1.1feature to Vi sual Age for Java. To see whether you have i nstal l ed thi s feature, go to File->Quick Start, sel ect Features on the l eft si de and DeleteFeature on the ri ght si de. Thi s wi l l show you al l i nstal l ed features (Fi gur e 120). Figure120. AvailableFeatures Add the feature i f i t has not been added to the Workbench. I n your pr oject (we used I TSO SG24 5471 as the pr oject name) cr eate a new package cal l ed itso.wasdb.ejb. Thi s wi l l contai n the enterpri se bean we devel op. Next go to the EJB pane i n the Wor kbench (Fi gur e 121). Now cr eate a new EJB gr oup i n the EJB pane. From the EJ Bs menu sel ect Add ->EJ B Group. Sel ect the pr oject (I TSO SG24 5471) and gi ve the EJB gr oup the name I TSO_EJ Bs. Chapter 10. Enterprise JavaBeans 135 Figure121. EJ B Development Pane: Adding an EJ B Group Create a Department Enterprise Bean To cr eate an enterpr i se bean: Fr om the context menu of the new EJB group sel ect Add ->EJ B. Our fi r st EJB wi l l be rel ated to the depar tment tabl e al r eady used thr oughout the book, so name the bean Department. As we want the contai ner to manage the persi stence ser vi ce, sel ect Entity Bean with container managed persistencefields (CMP) as the bean type. Sel ect the pr oject (I TSO SG24 5471) and the itso.wasdb.ejb package (Fi gure 122). 136 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure122. EJ B SmartGuide I n the next di al og of the SmartGui de you do not have to make any changes, so cl i ck on Finish. The SmartGui de has now created a very basi c framework for the EJB. I t shoul d have created thr ee i nterfaces and two cl asses: Department i nter face: Thi s curr entl y offer s no methods to be i mpl emented. Later on, thi s wi l l contai n the abstract method decl arati ons of al l methods that wi l l be i mpl emented by the DepartmentBean cl ass, whi ch r epr esents the busi ness l ogi c. DepartmentBean cl ass: Thi s cl ass wi l l contai n the actual busi ness l ogi c. The Smar tGui de has al ready created several methods for thi s cl ass, i ncl udi ng a method that cr eates the EJB. Because thi s i s an enti ty bean, the SmartGui de al so cr eated a primaryKey proper ty. Chapter 10. Enterprise JavaBeans 137 DepartmentBeanFinderHelper i nter face: Thi s shoul d be empty at the curr ent state. I t mi ght l ater contai n speci al i zed SQL sear ch stri ngs that al l ow a certai n or der wi thi n the vari ous EJB i nstances. DepartmentHomei nter face: Thi s contai ns a method to fi nd a speci fi c bean by i ts pr i mary key or cr eate a new bean wi th a new pri mary key. DepartmentKey cl ass: Thi s cl ass repr esents the pr i mary key for the enti ty bean. For the Department tabl e, thi s wi l l be mapped to the DEPTNO col umn. Add the Properties and Methods to the Bean Now we add the actual properti es and busi ness l ogi c to the skel eton cl asses. The pr oper ti es ar e basi cal l y nothi ng but the col umns fr om the department tabl e. The busi ness l ogi c i n thi s exampl e i s l i mi ted to get and set methods for the proper ti es. The department tabl e consi sts of the fol l owi ng col umns: DEPTNO, DEPTNAME, MGRNO, ADMRDEPT, and LOCATI ON. Therefore, the DepartmentBean contai ns the matchi ng pr oper ti es and al so the get and set methods for the properti es, except for the pr i mar y key property that shoul d not be al ter abl e. As descr i bed i n the pr evi ous step, the Smar tGui de al ready cr eated a pri mar y key pr oper ty. Because i t shoul d match the department tabl e, the fi rst acti on i s to add the deptNopr oper ty and make i t the pri mary key fi el d. Hi ghl i ght the DepartmentBean cl ass i n the Types pane and use the CreateField Smar tGui de to add a publ i c fi el d named deptNoof type Str i ng. Let the SmartGui de to create a get method for thi s property, but a set property i s not appr opr i ate for a pr i mary key (Fi gur e 123). Figure123. Adding a Field 138 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Now make the deptNo fi el d the pr i mary key fi el d. Cl i ck on the fi el ds i con i n the Typepane (Fi gur e 124). The Types pane i s now changed to a Fields pane. Her e you see al l the fi el ds (pr oper ti es) of the bean. I t contai ns now three properti es, the primaryKey property, an entityContext property, and the newl y created deptNo property. The primaryKey property i s cur rentl y the key fi el d (i t has the key i con on the ri ght si de) and i t i s a contai ner managed fi el d, i denti fi ed by the cup-l i ke i con on the ri ght si de. Figure124. SwitchingtotheFields Pane To make the deptNo property the pr i mar y key, r i ght-cl i ck on that deptNo entr y and sel ect KeyField. I t shoul d now show both i cons, the cup and the key. Chapter 10. Enterprise JavaBeans 139 Now we del ete the primaryKey property generated by the SmartGui de by removi ng i t from the bottom source pane. After del eti ng the pr i mar yKey property, the ejbCreatemethod i n the Methods pane r epor ts a probl em that we have to repai r. I n the method body of ejbCreate, r epl ace primaryKey by deptNo(deptNo = key.deptNo;). Ever ythi ng i s now r eady to add the rest of the pr oper ti es. Swi tch back to the Types pane and sel ect the DepartmentBean cl ass. Use the CreateField Smar tGui de to add the deptName, location, mgrNo, and admrDept properti es (al l publ i c, of type Str i ng, wi th getter and setter methods). By now your Methods pane shoul d be a bi t mor e fi l l ed. Next, make al l the getter and setter methods avai l abl e to the EJB Remote I nter face. To do thi s, ri ght cl i ck each getXXX and setXXX method, and sel ect Add To-> EJ B RemoteI nterface(Fi gur e 125). After thi s, each method contai ns a l i ttl e uni denti fi abl e i con on the r i ght, and the department i nterface offers al l the methods you have just added to the remote i nter face. Figure125. Add Methods totheRemoteI nterface 140 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Next, mar k al l the pr oper ti es we have defi ned to be persi stent. Swi tch back to the Fields pane, r i ght cl i ck on each fi el d and mark i t Container Managed (Fi gur e 126). Figure126. MarkingProperties Container Managed Map the Bean to the Schema The bean i s per si stent i n the rel ati onal database. We i mport the database schema and map the properti es of the bean to the col umns of the department tabl e. We descri be thi s onl y br i efl y because we covered schema mappi ng i n detai l i n Chapter 9, Per si stence Bui l der : Vi sual Age for Java on page 109. Star t the Persi stence Bui l der Schema Br owser fr om the menu EJ Bs -> Open To->DatabaseSchemas. Fr om the menu sel ect Schemas ->I mport / Export Schema ->I mport Schema fromDatabaseand name the new schema I TSO_Schema. Speci fy dr i ver, URL, user I D, and password (Fi gure 127). Figure127. Connection I nformation for theSchema I mport Chapter 10. Enterprise JavaBeans 141 Bui l d the tabl e l i st based on the I TSO qual i fi er and sel ect the DEPARTMENT tabl e (Fi gure 128). Figure128. Select theTabletoI mport We do not have to modi fy the i mpor ted schema (Fi gure 129). Cl ose the Schema Br owser. Figure129. Schema Browser after I mport 142 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server After i mporti ng the schema we perfor m the mappi ng. Open the Map Browser by sel ecti ng EJ Bs ->Open To->Map Schema. Fr om the Datastore_Maps menu sel ect New EJ B Group Map. Name the map I TSO_Map, sel ect the EJB gr oup and the schema (Fi gur e 130). Figure130. SpecifyingtheDatastoreMap for theEnterpriseBean The next step i s to associ ate the pr oper ti es of the EJB to the col umns of the department tabl e. Sel ect Table_Maps ->New TableMap ->Add Table Map with No I nheritanceand sel ect the DEPARTMENT tabl e (Fi gure 131). Figure131. Map Browser Chapter 10. Enterprise JavaBeans 143 We associ ate each pr oper ty to an attr i bute of the database tabl e. Open the Property Map Edi tor fr om the context menu of the DEPARTMENT tabl e map. Cl i ck on the Map Typei n each col umn to sel ect the Simplemappi ng and go on to sel ect the matchi ng col umn from the database tabl e (Fi gur e 132). When done, cl ose the property map edi tor and the Map Browser. Figure132. TheProperty Map Editor Generate the Code and Test Now everythi ng i s pr epared to generate the code: Ri ght-cl i ck on the EJB gr oup I TSO_EJ Bs and sel ect Generate->Deployed Code. Ri ght-cl i ck on the EJB group I TSO_EJ Bs and sel ect Generate->Test Client. As a r esul t the Types pane now shows more cl asses. To test an enterpri se bean Vi sual Age for Java contai ns a basi c EJB ser ver. To add the enter pri se bean to the EJB ser ver, ri ght-cl i ck on the I TSO_EJ Bs EJB gr oup and sel ect Add To->Server Configuration (Fi gure 133). 144 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure133. EJ B Server Configuration Dialog Starting the EJB Server in the Test Environment Now we have to start each of the ser vi ces: Star t the Location ServiceDaemon. Ri ght-cl i ck on i t and sel ect Start Server. Next star t the Persistent NameServer the same way. Befor e you star t the EJB ser ver i tsel f, ensur e that the properti es ar e cor rect. Ri ght-cl i ck on the EJ B Server and sel ect Properties. Make sure the database URL (jdbc:db2:itsowdb), user I D (I TSO) and password (itso) are cor rect (Fi gur e 134). Figure134. EJ B Server Properties Chapter 10. Enterprise JavaBeans 145 Fi nal l y star t the EJB ser ver. The consol e shoul d di spl ay al l the server s as shown i n Fi gur e 135. The ser ver i s now r eady and the enter pri se bean i s depl oyed i n the test envi r onment. Figure135. EJ S ConsoleOutput Wai t for al l the ser ver s to be ready before conti nui ng wi th testi ng. Using the Test Client Now we can test the enter pri se bean wi th the test cl i ent we generated a few steps earl i er. Sel ect the Department EJB i n the EJ B Server Configuration Window and cl i ck on the Run Test Client button (the yel l ow runni ng man i con i n Fi gure 133) to open the test cl i ent wi ndow. The test cl i ent wi ndow i s the same for al l enterpri se beans (Fi gure 136). 146 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure136. Test Client Cl i ck the Connect Button and the test cl i ent presents the home i nter face of our depar tment bean (Fi gur e 137). Thi s i s onl y used to fi nd or create an i nstance of the depar tment enter pri se bean. Figure137. TheHomeI nterface Chapter 10. Enterprise JavaBeans 147 Now we r etri eve a department wi th a gi ven pr i mar y key: Sel ect the findByPrimaryKey entr y i n the l i st of methods on the l eft si de. Cl i ck on the Newbutton i n the parameter s l i st on the ri ght si de. Sel ect new DepartmentKey(String) i n the constructor s pane and enter a depar tment number (for exampl e, E21) as the par ameter i n the Depar tmentKey di al og (Fi gur e 138). Cl i ck on the Send button and then on the Donebutton. Figure138. Parameter Specification for theDepartmentKey Back i n the HomeI nterfaceDialog (Fi gure 137) cl i ck the Send button and the HomeI nterfaceshoul d change to the RemoteI nterface, whi ch represents the remote i nter face for the actual busi ness l ogi c. You may now execute the methods of the enter pri se bean; for exampl e, to r etri eve the department name, sel ect the getDeptNamemethod and cl i ck the Send button (Fi gur e 139). You can use the setXxxxx methods to change the val ues i n the department bean r etri eved. Each Send of a set method changes the col umn val ue i n the tabl e. (You can open a DB2 command wi ndow to veri fy the changes i n the tabl e.) 148 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure139. Test Client PresentingtheRemoteI nterface You may now pl ay around wi th the test cl i ent. For i nstance, you mi ght cr eate a new DepartmentBean usi ng the home i nterface, and use the setXxxx methods to set the pr oper ti es and ther efor e the col umn val ues i n the department tabl e. Note that the Send key for the create(DepartmentKey) method r eturns wi th an err or 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 col umns DEPTNAME and ADMRDEPT wer e defi ned as not null. We have to pr ovi de i ni ti al val ues. We can change the create(DepartmentKey) method i n the EJB Workbench pane to set defaul t val ues for the requi red fi el ds: public void ejbCreate(DepartmentKey key) { // All CMP fields should be intialized here. deptNo = key.deptNo; deptName = "Unknown"; admrDept = " "; } Wi th thi s change the cr eati on of a new depar tment wor ks. The department name and the other fi el ds (col umns) can be changed afterwar ds usi ng the set methods. Chapter 10. Enterprise JavaBeans 149 Deploy the Enterprise Bean to WebSphere The next step i s to extract the enterpr i se bean and take i t i nto a real envi ronment, whi ch i s the WebSphere Appl i cati on Server. WebSphere provi des an i nfrastructure to r un a contai ner-managed persi stence enti ty bean coded accor di ng the Suns EJB speci fi cati on. To depl oy a bean wi thi n the WebSpher e Appl i cati on Ser ver, perfor m the fol l owi ng steps: Fi r st, expor t a JAR fi l e contai ni ng the bean. You have two choi ces here: One way i s to export an al ready depl oyed ver si on of the bean. Vi sual Age for Java can do thi s for you. The advantage of thi s method i s that WebSpher e keeps the mappi ng from the bean properti es to the tabl e attr i butes. To export the JAR fi l e, r i ght-cl i ck on the depar tment EJB i n the EJ Bs pane and sel ect Export ->EJ S J ar. You shoul d pl ace the resul ti ng JAR fi l e i n the deployableEJ Bs di rectory of WebSpher e (for exampl e, c:\WebSphere\AppServer\deployableEJBs\DepartmentEJS.jar). The other way i s to expor t just the bean code and l et WebSphere do the depl oyment process. But thi s has the effect that the mappi ng whi ch we have just done wi l l be l ost. Dur i ng the depl oyment process, WebSphere wi l l tr y to create a new schema and a new tabl e i n the schema, whi ch refl ects the pr oper ti es of the bean. I f we had started from scr atch, thi s method mi ght be fi ne, but because we al ready have some data i n our database, thi s i s not appropri ate. Export the JAR fi l e (Export ->Export EJ B J ar) and WebSphere wi l l do the mai n par t of the depl oyment process. The next step i s to generate a new EJB contai ner i n WebSpher e. Thi s contai ner hol ds the database speci fi cati on: URL, user I D, and passwor d. I f WebSphere supports other database systems for contai ner-managed beans thi s mi ght be the pl ace where you must al so speci fy the dri ver. But because WebSpher e cur rentl y onl y suppor ts DB2, we do not have to provi de a dr i ver. To create a new contai ner, open the WebSpher e admi ni strati on appl et. Go to the EnterpriseJ ava Services ->Global Settings. Make sure EJS i s enabl ed and the host name matches your machi ne name (Fi gure 140). I f you use localhost, l ater on you wi l l not be abl e to access the EJB remotel y. Apparentl y the nami ng ser vi ce on the machi ne runni ng the EJB server di ffer enti ates between localhost and servername. 150 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure140. WebSphereGeneral EJ B Settings I n the Containers secti on add a new contai ner wi th the name I TSOContainer. Sel ect the contai ner and pr ovi de the speci fi cati on: Because we have wri tten an enti ty bean, we wi l l use the com.ibm.ejs.container.EJ SEntityContainer cl ass. Thi s i s one of two contai ner cl asses whi ch WebSphere provi des. The other contai ner cl ass, whi ch i s for sessi on beans, i s accor di ngl y named com.ibm.ejs.container.EJ SSessionContainer. Next we have to speci fy the JDBC URL: jdbc:db2:itsowdb. The di r ector y i n whi ch to put the depl oyed beans i s deployedEJ Bs. Fi nal l y, speci fy the user I D and passwor d (I TSO and itso). At the bottom of thi s pane, you wi l l noti ce a l i st box that shows the beans that are al ready depl oyed i n the sel ected contai ner. Because we have just cr eated a new contai ner, no beans are l i sted here. Cl i ck on Save to preser ve the changes (Fi gure 141). Chapter 10. Enterprise JavaBeans 151 Figure141. WebSphereContainer EJ B Settings Now we ar e r eady to depl oy the bean. I n the EJ B J ar Files pane (Fi gur e 142), sel ect the DepartmentEJ S.jar on the l eft and cl i ck the Deploy button. Figure142. EJ B J ar FilePane I n the Deploy J ar Filedi al og, sel ect the I TSOContainer from the combobox and cl i ck on Deploy (thi s di al og i s not shown). 152 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server WebSphere shoul d now pr esent a di al og box, warni ng you that the depl oyment was al ready done (Fi gure 143). Do not regenerate the jar fi l e, onl y r edepl oy i t (cl i ck on RedeployExisting). I f you r egener ate, WebSphere wi l l l oose the mappi ng fr om the bean pr oper ti es to the database tabl e and wi l l create a new schema and tabl e, whi ch i s not what we want to happen. Figure143. Redeployment Warning You shoul d r ecei ve a message that the Department bean was depl oyed successful l y. To make the bean avai l abl e, i t i s necessar y to r estar t WebSphere. Stop the WebSphere Ser vl et Ser vi ce and the I BM HTTP Server and r estar t the HTTP Ser ver (whi ch i n tur n shoul d start up WebSphere as wel l ). You can test the depl oyed bean by usi ng the test cl i ent from Vi sual Age for Java. After starti ng the test cl i ent, connect to the bean usi ng the URL: iiop://hostname:9019 WebSphere wi l l not star t the EJB servi ces properl y i f ther e ar e any enti ty contai ner s that ar e i nval i d i n ter ms of usi ng a non-exi stent or non-accessi bl e database. For exampl e, i f you di d not r eate the sampl e database fr om DB2, then the defaultEntityContainer wi l l not be abl e to star t because the database i t uses i s not there. I n case of such a fai l ur e, WebSphere apparentl y does not start up the servi ces at al l . Thesimplest and safest solution is to removeall unused containers. Do this by inspectingall containers in respect to the deployed beans they contain. Notice Chapter 10. Enterprise JavaBeans 153 Access the Department Bean from a Servlet Now that our bean i s depl oyed, how can we access i t? I n our fi rst exampl e, we access the enter pri se bean through a servl et. Thi s ser vl et i s very si mpl e and contai ns nothi ng exci ti ng except for the methods to cr eate or fi nd our enter pr i se bean. The ser vl et enabl es the user to r etri eve a bean and to show and update i ts properti es. The servl et (DepartmentEJ BServlet cl ass i n itso.wasdb.ejb.servlet package) contai ns the fol l owi ng methods: doPost and doGet: Both methods just cal l the performTask method. Thi s makes the ser vl et i ndependent of the sel ected HTTP method to tr ansfer the form data. We wi l l not l i st these methods her e, i nstead refer to Fi gur e 85 on page 101. performTask: Based on the r equest, thi s method di r ects the fl ow ei ther to the getDepartment method or the updateDepartment method. getParameter: Thi s i s a si mpl e hel per method to r etri eve a par ameter from an HTTP request object. See Fi gur e 84 on page 100. init: Thi s i ni ti al i zes the ser vl et. Thi s method contai ns the code to start a connecti on to the EJB ser ver. createOrtFindDepartment: Based on a gi ven key, thi s method tr i es to fi nd a depar tment; and i f that department does not exi st, i t cr eates a new one. getDepartment: Thi s method retr i eves a depar tment bean and pr esent i ts contents i n an HTML for m that enabl es the user to update the bean. I t al so attaches the bean to the sessi on for usage i n the next i nteracti on. updateDepartment: Thi s method perfor ms the update of the contents of the bean. Based on the form data, i t uses the setter methods of the bean that was r etri eved i n the getDepartment method. Class Declaration The DepartmentEJ BServlets cl ass decl ar ati on i s shown i n Fi gur e 144. I t contai ns two cl ass var i abl es: The departmentHomeVar i abl e represents the home i nter face of the DepartmentBean The initContext represents the i ni ti al context of the nami ng ser vi ce. Thi s makes i t possi bl e to retr i eve the home i nterface of the depar tment bean. 154 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure144. DepartmentEJ BServlet Class Declaration Perform Task Method The performTask method i s si mpl e. Dependi ng on the request, i t cal l s ei ther the getDepartment or the updateDepartment method (Fi gur e 145). Figure145. DepartmentEJ BServlet performTask Method Initialization The init method (Fi gure 146) i ni ti al i zes the servl et. I t retr i eves the i ni ti al context, whi ch provi des a starti ng poi nt for nami ng and di r ectory oper ati ons. Once we have thi s i ni ti al context, we can use i t to l ook up other contexts and objects. Thi s i s done i n the next few l i nes of code. The i ni ti al context i s used to l ook up an object that i s regi stered under the name Department. Usi ng a stati c hel per method from the gener ated code, thi s object i s then cast to an object of type DepartmentHome, whi ch i s the home i nter face of the depar tment bean and ser ves for creati ng and fi ndi ng of a depar tment enter pri se bean. The r esul ti ng object i s stored i n the departmentHomecl ass var i abl e . 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 ... } Chapter 10. Enterprise JavaBeans 155 Figure146. DepartmentEJ BServlet init Method Retrieve a Department Bean The next method to l ook at i s the getDepartment method that uses the home i nter face to ei ther cr eate a new enterpr i se bean or fi nd an al ready exi sti ng bean based on the pri mar y key gi ven i n the HTTP request (Fi gure 147). We do not descr i be the method i n detai l , but wi l l concentr ate on the i nter esti ng parts that are mar ked i n bol d 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 Java properties.put(javax.naming.Context.PROVIDER_URL, "iiop://sonoma:9019"); // IBM name services properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.jndi.CosNaming.CNInitialContextFactory"); try { initContext = new InitialContext(properties); Object obj; // lookup the home interface using the JNDI name System.out.println("Retrieving the home interface..."); Object o = initContext.lookup("Department"); // this is the JNDI name if (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()); } } 156 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure147. DepartmentEJ bServlet 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 writer java.io.PrintWriter out = response.getWriter(); // Get the deptNo to look for String 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>"); } Chapter 10. Enterprise JavaBeans 157 The fi r st poi nt of i nterest i s where the actual enter pri se bean i s obtai ned. Thi s i s done by the createOrFindDepartment method based on a pr i mary key gi ven i n the HTTP r equest. The contents of thi s bean are then pr esented i n an HTML form. Thi s l eads to the next i nter esti ng poi nt: The bean i tsel f i s attached to the curr ent HTTP sessi on for l ater usage i n the updateDepartment method. Create or Find a Department Bean Now l et us i nspect the createOrFindDepartment method (Fi gure 148). Thi s method tri es to fi nd an enterpr i se bean, and i f i t cannot fi nd one, i t creates a new enter pri se bean. Both oper ati ons uti l i ze the home i nter face of the department bean. I n any case, i t wi l l return the bean to the cal l er. Figure148. DepartmentEJ BServlet createOrFindDepartment Method Update the Department Bean The l ast method that i s i mportant for our ser vl et i s the updateDepartment method (Fi gure 149). The i nter esti ng parts ar e agai n shown i n bol d face. Basi cal l y, the sessi on that was created i n the getDepartment method i s used to r etri eve the attached department bean. Then, based on the for m data, i t fol l ows a si mpl e sequence of setXxxx i nvocati ons of the depar tment bean. That i s 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; } 158 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure149. DepartmentEJ BServlet updateDepartment Method Test the Servlet in VisualAge for Java Star t the WebSpher e Test Envi ronment (SERunner cl ass) and make sure that the EJB ser ver i s r unni ng (see Gener ate the Code and Test on page 143). Comment one l i ne i n the i ni t method (Fi gur e 146 on page 155): // properties.put(javax.naming.Context.PROVIDER_URL, "iiop://sonoma:9019"); I nvoke the servl et wi th the URL: http://127.0.0.1:8080/servlet/itso.wasdb.ejb.servlet.DepartmentEJBServlet? deptNo=E21 Executi ng the servl et r esul ts i n the browser output shown i n Fi gure 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>"); } Chapter 10. Enterprise JavaBeans 159 Test the Servlet in WebSphere Now l et us try to i nvoke the servl et wi th the depl oyed enter pri se bean under WebSphere. Expor t the cl ass fi l e of the servl et from Vi sual Age for Java to the WebSphere servl ets di r ector y: c:\WebSphere\AppServer\servlets\itso\wasdb\ejb\servlet I nvoke the servl et wi th the URL: http://hostname/servlet/itso.wasdb.ejb.servlet.DepartmentEJBServlet? command=getDepartment&deptNo=E21 Executi ng the servl et r esul ts i n the browser output shown i n Fi gure 150. Figure150. DepartmentEJ BServlet in a Browser You may now change the contents of the bean and cl i ck on Update. Keep i n mi nd that you shoul d not exceed the l engths of the fi el ds; other wi se, the update wi l l not succeed. For exampl e, the Admr. Department may not be l onger than three char acters. I f the update was successful , the servl et wi l l l et you know. Cl i ck on Back to retr i eve the enterpr i se bean agai n and veri fy that the bean has changed. 160 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Access the Department Bean from an Application I n the same way that we have used a ser vl et to access our enter pr i se bean, we mi ght want to use an appl i cati on or an appl et. We wi l l devel op a si mpl e panel that works the same way our ser vl et does. The user can enter a department number ; i f the depar tment exi sts the appl et wi l l show i ts content, i f not i t wi l l create a new department bean. Thi s panel mi ght be added to an appl i cati on or to an appl et. Create the GUI Layout We use Vi sual Age for Java to devel op the appl et. Create a new package cal l ed itso.wasdb.ejb.client. I n thi s package create a new cl ass cal l ed DepartmentPanel. Deri ve thi s cl ass fr om the Swi ng JPanel cl ass and mark the Composetheclass visually checkbox i n the SmartGui de. I n the Vi sual Composi ti on Edi tor, desi gn the panel . The fi nal panel wi th connecti ons i s shown i n Fi gure 151. Figure151. Department Panel with All Connections 1 2 2 3 4 5 6 6 6 Chapter 10. Enterprise JavaBeans 161 Create the Connections 1. Fi r st, we have to cr eate a connecti on to the ser ver to retr i eve the i ni ti al context and the home i nter face of the department bean. Thi s r equi r es a method to i ni ti al i ze the context and the home i nter face based on the server name. We wi l l use a new method cal l ed createOrFind. For the Create/ Find Department button, sel ect Event toCodefr om the context menu and enter the createOrFind method code (Fi gur e 152). Noti ce that the code i s al most the same as for the servl et (Fi gure 148 on page 157), and agai n the err or handl i ng i s onl y very r udi mentary. 2. For the par ameters of the method, sel ect the text fi el d next to the Servernamel abel and the text fi el d next to the Create/ Find Department button. 3. The createForFind method pr ovi des our department bean as a r esul t. To be mor e preci se, i t pr ovi des an i mpl ementati on of the Department i nter face. To store thi s object we use a vari abl e named department and we use the context menu to change i ts type to Department. Ther efor e, we connect the normalResult of the createOrFind method to our department var i abl e (this property). 4. Now that department i s a val i d object, we connect each pr oper ty of department (admrDept, location, mgrNo, and deptName) to the matchi ng text properti es of the text fi el ds. 5. For the Updatebutton we connect actionPerformed to the setLocation method of department. Because the setLocation method r equi r es a parameter, we provi de i t wi th the text pr oper ty of the depar tment name text fi el d. 6. Next, we do the same for the other pr oper ti es: admrDept, mgrNo, and deptName. 162 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure152. DepartmentPanel createOrFind Method public itso.wasdb.ejb.Department createOrFind(String key, String adress) { // Get the initial context if (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 Java properties.put(javax.naming.Context.PROVIDER_URL, "iiop://" + adress + ":9019"); // IBM name services properties.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 name try { System.out.println("Retrieving the home interface..."); Object o = initContext.lookup("Department"); // this is the JNDI name if (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; } Chapter 10. Enterprise JavaBeans 163 Test the Applet or Application Because Vi sual Age for Java automati cal l y creates a main method for testi ng pur poses, we can al ready test the panel . The normal way i s to i mbed the DepartmentPanel i n an appl et or appl i cati on. We do not show how thi s process i s done because i t i s just a tr i vi al step. However, the sampl e reposi tor y provi des an appl et and an appl i cati on that use the DepartmentPanel. To test the panel , execute i t, enter your server name and a val i d depar tment number, and cl i ck Create/ Find Department button (Fi gur e 153). Figure153. Department Panel Displaying theDepartment Bean We were not abl e to access the depar tment bean from an appl et runni ng i nsi de a browser, al though i t was possi bl e to run the appl et i nsi de a r emote appl et vi ewer. Presumabl y, thi s has somethi ng to do wi th the secur i ty r estri cti ons under whi ch the appl et has to run i nsi de a browser. Notice 164 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Developing a Bean Managed Persistence Entity Bean I n thi s secti on we wi l l devel op an enti ty bean that manages i ts persi stence i tsel f. For thi s exampl e, we wi l l take the second tabl e of our sampl e database and devel op a bean that stor es i ts state to the empl oyee tabl e of the database. We wi l l agai n star t wi th the SmartGui de of Vi sual Age for Java to cr eate the bean. Create an Employee Enterprise Bean with the SmartGuide Si mi l ar to the pr ocess of addi ng a contai ner managed bean, we now have to add another bean to our I TSO_EJ Bs group (sel ect Add To->EJ B). Create a new enter pri se bean, but thi s ti me sel ect Entity Bean with Bean- managed Persistence(BMP) for the bean type. Name i t Employeeand add i t to the itso.wasdb.ejb package (Fi gur e 154). Figure154. Adding a BMP Bean Chapter 10. Enterprise JavaBeans 165 Add Properties and Methods Now we add the properti es to the bean. Thi s i s si mi l ar to the steps we have done for the CMP bean, except that i t i s not possi bl e to mark a pr oper ty to be contai ner-managed, and there i s al so no way to mar k a property to be the pri mar y key fi el d (Fi gure 155). For each col umn of the empl oyee tabl e, cr eate a matchi ng pr oper ty wi th getter s and setters (no setter for the empl oyee number ). Add al l getters and setter to the remote i nter face (Add To->EJ B RemoteI nterface). Figure155. Properties in theWorkspaceView The pr oper ti es are l i sted i n Tabl e 3. Table3. Properties of theEmployeeBean Type Name Type Name Str i ng empNo Str i ng fi r stName Str i ng mi dI ni t Str i ng l astName Str i ng wor kDept Str i ng phoneNo java.uti l .Date hi r eDate Str i ng job Str i ng sex java.uti l .Date bi rthDate doubl e sal ar y doubl e bonus doubl e comm shor t edLevel i tso.wasdb.ejb. Empl oyeeStorage stor age (pr i vate, no getter /setter ) 166 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Provide the Employee Bean with Persistence Functionality The onl y thi ng, apart fr om addi ti onal busi ness functi onal i ty, i s to provi de the bean wi th the functi onal i ty that i t can persi st i tsel f to some database system. To i mpl ement the per si stence, we have to understand whi ch methods of the bean ar e i nvoked by the EJB contai ner and what the purpose of each method i s. Vi sual Age for Java by defaul t creates the fol l owi ng methods: publ i c voi d ej bLoad(): Thi s method i s i nvoked by the contai ner to synchroni ze the bean accordi ng to the state represented i n the database. Thi s means that the enter pri se bean has to be abl e to r efr esh i tsel f from the tabl e. publ i c voi d ej bStore(): Thi s i s the counter part of the ejbLoad method. I t synchr oni zes the database accor di ng to the state of the enter pri se bean. The bean has to abl e to wr i te i ts state i nto the database. publ i c Empl oyeeKey ej bFi ndByPri maryKey(Empl oyeeKeykey): Thi s method retr i eves an object wi th a gi ven key from the database and returns the key. publ i c Empl oyeeKey ej bCreate(Empl oyeeKey key): Thi s method i s i nvoked when the cl i ent requests a new enter pr i se bean usi ng the home i nter face method create(...). Thi s method i s usual l y the pl ace to val i date the argument gi ven from the cl i ent and to i nsert a new row i n the database tabl e that repr esents the contents of the enterpr i se bean. publ i c voi d ej bRemove(): The contai ner i nvokes thi s method to end the l i fe of thi s enter pri se bean. Thi s i s the pl ace to del ete the r ecord that represents thi s bean from the database. publ i c voi d ej bActi vate(): Thi s method i s i nvoked when the contai ner pi cks an i nstance from the pool and assi gns i t to a speci fi c enter pri se bean object. Accor di ng to the EJB speci fi cati on, thi s i s not the pl ace to read the state of the bean fr om a database; thi s shoul d be done i n the ejbLoad method. The ejbActivatemethod gi ves the bean the chance to use, i ni ti al i ze, or acqui re addi ti onal r esources. Thi s method i s i nvoked by the contai ner pr i or to the i nvocati on of ejbLoad. publ i c voi d ej bPassi vate(): Thi s i s the counterpar t of the ejbActivate method. I t gi ves the enterpr i se bean the chance to r el ease any resources that were acqui red duri ng the ejbActivatemethod. Thi s method i s cal l ed di rectl y pri or to the i nvocati on of the ejbStoremethod. There are some mor e methods, but at the moment those ar e of no i nterest. We have to i mpl ement the ejbLoad, ejbStore, ejbFindByPrimaryKey, ejbCreate, and ejbRemovemethods. Because we do not use any addi ti onal resources, we can ski p the ejbActivateand ejbPassivatemethods. Chapter 10. Enterprise JavaBeans 167 To make the bean per si stent, we use the I BM data access beans. The usage i s capsul ated i n the EmployeeStoragecl ass. Thi s cl ass i s r esponsi bl e to cr eate a new r ow, to r etri eve a row, to update a row, or to del ete a row fr om the empl oyee tabl e of our database. Therefore, among the attri butes that represent the actual empl oyee object, the EmployeeBean hol ds a pri vate i nstance of an EmployeeStoragecl ass, named storage. I n the fol l owi ng code sni ppets, we onl y descri be how to fi nd and update an enti ty bean and the respecti ve database r ecord. The acti ons to remove or cr eate a new enti ty bean ar e ver y si mi l ar. Methods of the Entity Bean The code for the ejbFindByPrimaryKey method (and for most methods of the enti ty bean) i s very short and si mpl e. The mai n work i s done i n the EmployeeStoragecl ass. I n thi s method we cr eate a new i nstance of the EmployeeStorage(i f not al r eady there) and i nvoke the findEmployeemethod wi th the i nstance of the enter pr i se bean and the pri mary key (Fi gure 156). Figure156. EmployeeBean ejbFindByPrimaryKey Method The ejbStoremethod to store the enti ty bean and synchr oni ze i ts contents wi th the database i s al so rather si mpl e. The onl y thi ng done here i s to i nvoke the update method of the stor age cl ass (Fi gur e 157). Figure157. EmployeeBean ejbStoreMethod 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()); } } 168 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Fi gur e 158 shows some of the other methods. Figure158. 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; } Chapter 10. Enterprise JavaBeans 169 The EmployeeStorage Class Now we i mpl ement the EmployeeStoragecl ass, and speci fi cal l y, the two methods of the stor age cl ass that wer e used i n the two methods of the enti ty bean, namel y the findEmployeemethod and the updateEmployeemethod. Class Declaration We star t wi th the decl ar ati on of the cl ass (Fi gur e 159). Figure159. EmployeeStorageClass 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; // Oracle final static String URL = "jdbc:oracle:thin:@sonoma:1521:orcl"; final static String DRIVERNAME = "oracle.jdbc.driver.OracleDriver"; static int database = 3; // SQL Server 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"; 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; } 170 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The Empl oyeeStorage cl ass defi nes the database that wi l l be used, the user I D, and the password. I t al so contai ns stati c references to the di fferent SQL statements: sel ect, i nsert and del ete. The actual statements wi l l be created l ater, we onl y defi ne the str i ng constants her e. Noti ce that no update stri ng i s defi ned. The update i s done through the data access bean. We do not have to defi ne anythi ng for thi s. At the ver y bottom we defi ne a nonstati c SelectResult. Thi s resul t wi l l be used to update a row fetched from the database. Thi s exampl e uses the DB2 database, but we coul d have used any other database that provi des the I TSOWDB database as wel l , al though the code di ffer s a l i ttl e bi t (see Di ffer ent Mappi ng of SQL Types on page 264). Initializing the Meta Data The next method we descri be i s the method that i ni ti al i zes the meta data for the sel ect statement. Thi s method i s stati c because the actual sel ect statement i s the same and i ndependent of speci fi c i nstances of the enti ty bean (Fi gur e 160). Figure160. I nitializetheSelect Statement static void initSelect() throws DataException { selectMetaData = new StatementMetaData(); selectMetaData.setSQL(SELECT); // Use the default mapping, Oracle seems to have problems otherwise selectMetaData.addParameter("EMPNO", String.class, Types.CHAR); // Next define all ouput parameter in the same way selectMetaData.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) { //DB2 selectMetaData.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 query selectMetaData.addTable("ITSO.EMPLOYEE"); } Chapter 10. Enterprise JavaBeans 171 The code of thi s method i s speci fi c for DB2, because Or acl e and the SQL Server di ffer i n they way they map SQL types (see Di fferent Mappi ng of SQL Types on page 264). Due to that, we had to use di ffer ent speci fi cati ons for the meta data for the di fferent databases. The sampl e code of thi s cl ass contai ns the code for al l thr ee database systems. Constructor The constructor cal l s the i ni ti al i ze method to set up a database connecti on and the meta data for the sel ect, i nser t, and del ete statements (Fi gur e 161). Figure161. EmployeeBean ejbStoreMethod The i ni tDel ete and i ni tI nsert methods ar e si mi l ar to the initSelect method. Find an Employee As we saw i n Fi gur e 156 on page 167 the ejbFindByPrimaryKey method used the findEmployeemethod of the EmployeeStoragecl ass. Thi s method uses the meta data for the sel ect statement, whi ch was i ni ti al i zed i n the initSelect method. The fi ndEmpl oyee method i s r ather si mpl e: A new SelectStatment i s created whi ch uses the database connecti on and the prepared meta data to r un a quer y agai nst the database. I f a r ow was found, the empl oyee bean i s fi l l ed wi th the col umn contents of that row (Fi gur e 162). Noti ce that the method does not cl ose the resultSet, and that thi s resultSet i s an i nstance var i abl e of the cl ass. 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 } 172 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure162. Find an Employee Update an Employee The updateEmployeemethod changes a r ecord i n the database based on the data i n the empl oyee bean. Thi s method uses the resultSet that was assi gned i n the fi ndEmpl oyee method. Thi s makes the update step qui te si mpl e (Fi gure 163). Based on the resultSet fr om the fi ndEmpl oyee method, the new val ues for the row ar e set from the bean. Fi nal l y, the resultSet i s updated. The resultSet i s not cl osed i n the updateEmpl oyee method; i t i s cl osed when the contai ner i nvokes the ejbPassivatemethod, whi ch cal l s the closemethod of the EmployeeStoragecl ass. 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 query select.setParameter("EMPNO", key); // and execute the query select.execute(); // Retrieve the result set resultSet = select.getResult(); if (resultSet.getNumRows() == 0) throw new java.rmi.RemoteException("No Record found"); // Now get the resulting column by name empl.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()); } } Chapter 10. Enterprise JavaBeans 173 The method uses a smal l date2Timestamp method that conver ts a java.util.Dateobject to a java.sql.Timestamp object that i s requi red by Or acl e. Thi s code i s speci fi c to the Oracl e database. Figure163. UpdatetheDatabase Delete an Employee The deleteEmployeemethod removes the database r ecord wi th a gi ven key. public void deleteEmployee(String key) throws DataException { SQLStatement delete = new SQLStatement(); delete.setConnection(dbConn); delete.setMetaData(deleteMetaData); // Now set the Parameters for the delete delete.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) { //DB2 Calendar 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) { //Oracle resultSet.setColumnValue("HIREDATE", date2Timestamp(empl.getHireDate())); resultSet.setColumnValue("BIRTHDATE", date2Timestamp(empl.getBirthDate())); resultSet.setColumnValue("EDLEVEL", new BigDecimal(Integer.toString(empl.getEdLevel()))); } resultSet.updateRow(); } 174 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Testing the Employee Bean Befor e testi ng the empl oyee bean, you have to generate the home and hel per cl asses. Sel ect EJ Bs ->Generate->Deployed Codefor the empl oyee enter pr i se bean. Start the EJB Server Add the I TSO_EJBs to the server (Add To->Server Configuration) and star t the server (see Starti ng the EJB Server i n the Test Envi r onment on page 144). Be sure to veri fy the pr oper ti es of the server befor e starti ng i t (see Fi gur e 134 on page 144). Test Client You can use the test cl i ent agai nst the empl oyee bean and r etri eve an empl oyee and update i ts pr oper ti es. Generate the test cl i ent code (sel ect Generate->Test Client) and start i t (see Usi ng the Test Cl i ent on page 145). Access the Employee Bean from a Servlet For the empl oyee enterpr i se bean we created a servl et (EmployeeEJ BServlet) that accesses the empl oyee enter pri se bean. The str uctur e of the ser vl et i s exactl y the same as the DepartmentEJ BServlet descr i bed i n Access the Department Bean from a Ser vl et on page 153, ther efor e we do not l i st the compl ete i mpl ementati on her e. The servl et consi sts of the fol l owi ng methods: init i ni ti al i zes the context and deter mi nes the home i nter face of the empl oyee bean. doGet and doPost, whi ch both cal l the performTask method. performTask deci des whether an empl oyee shoul d be retr i eved (i nvoke getEmployee) or updated (i nvoke updateEmployee). findEmployeer etri eves an empl oyee bean based on the empl oyee number by usi ng the home i nter face of the empl oyee bean. getEmployeeuses findEmployeeto retr i eve the empl oyee bean and di spl ay i t (parti al l y) i n an HTML form (Fi gure 164). Chapter 10. Enterprise JavaBeans 175 Figure164. Retrieveand Display theEmployeeBean 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 writer java.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; } 176 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server updateEmployeesets the properti es of the bean based on the i nput the user has made i n the HTML for m (Fi gure 165). Figure165. Set theProperties of theEmployeeBean Testing the Servlet Star t the WebSpher e Test Envi ronment and make sure that the EJB Ser ver i s runni ng. Open a browser and enter the URL: http://127.0.0.1:8080/servlet/itso.wasdb.ejb.servlet.EmployeeEJBServlet? empNo=000010 The r esul t of the empl oyee ser vl et l ooks si mi l ar to the depar tment ser vl et (Fi gure 166). Figure166. EmployeeEJ BServlet 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 writer java.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>"); } Chapter 10. Enterprise JavaBeans 177 Deployment of the Employee Bean to WebSphere The empl oyee enter pri se bean i s depl oyed i n the same way as the department bean, but ther e ar e a few di ffer ences: Export the JAR fi l e (sel ect Export ->EJ S J ar). I n the expor t di al og, cl i ck on the Details button and add the Empl oyeeStor age cl ass. I t i s requi red at runti me to access the database. Name the fi l e EmployeeEJ S.jar. I n the WebSphere admi ni str ati on di al og for Enter pri se Java Servi ces, the gl obal setti ngs are fi ne (Fi gur e 140 on page 150), and we can use the same I TSOContai ner (Fi gur e 141 on page 151). Sel ect the EmployeeEJ S.jar fi l e on the EJB Jar Fi l es page (Fi gur e 142 on page 151) and cl i ck on Deploy. Sel ect the I TSOContai ner, and cl i ck on Redeploy Existing i n the war ni ng di al og (Fi gure 143 on page 152). Star t the test cl i ent i n Vi sual Age for Java and connect to the depl oyed empl oyee enter pri se bean. 178 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 179 11 WebSphere Studio I n thi s chapter we br i efl y i ntr oduce the WebSphere Studi o tool s. We then descri be i n more detai l the servl et generati on wi zar ds that al l ow easy cr eati on of ser vl ets wi th r el ati onal database access. 180 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server WebSphere Studio Tools WebSphere Studi o can hel p a Web team bui l d powerful , e-busi ness Web si tes packed wi th featur es and i nter acti on, wi thout r el yi ng on the Common Gateway I nter face (CGI ) and Acti ve Ser ver Pages (ASP). WebSphere Studi o combi nes easy-to-use wi zards wi th si te desi gn and Java devel opment tool s, si mpl i fyi ng and speedi ng the appl i cati on devel opment process. I t combi nes graphi cal devel opment wi zards wi th tool s for Web si te desi gn and Java devel opment. These wi zar ds and tool s si mpl i fy and speed the appl i cati on devel opment process, and i ncl ude: Web Development WorkbenchA Web si te pr oject organi zer and l aunch pl atfor m. Servlet generation wizardsFor bui l di ng Java ser vl ets to access JDBC databases and JavaBean components. VisualAgefor J ava, Professional Edition V2.0I BM's Java appl i cati on devel opment envi r onment for bui l di ng Java appl i cati ons, appl ets, ser vl ets and JavaBean components. NetObjects Fusion V3.0Al l ows Web si te devel oper s to desi gn and produce an enti re Web si te, i ncl udi ng i ndi vi dual pages and al l l i nks. I t featur es automated si te bui l di ng, automati c l i nk management, r emote database access, and desi gn and publ i shi ng capabi l i ti es. NetObjects BeanBuilder V1.0The vi sual authori ng tool for combi ni ng JavaBeans and Java appl ets, BeanBui l der al l ows i ndi vi dual s overseei ng the content of onl i ne busi ness processes to create more compel l i ng, hi ghl y i nter acti ve Web si tes. NetObjects ScriptBuilder V3.0Combi nes a text-based scri pt edi tor and devel opment tool s for creati ng and edi ti ng HTML, scr i pt, and JavaSer ver Pages (JSP). I n thi s chapter we onl y cover the ser vl et wi zar ds and show how to use them to create si mpl e database access ser vl ets, the cor respondi ng JSPs, and JavaBeans. Chapter 11. WebSphere Studio 181 Installation and Configuration Duri ng our wor k we used WebSphere Studi o 3.0 Beta 2 whi ch was downl oadabl e fr om http://www.software.ibm.com/webservers/. Al though WebSphere Studi o al l ow the speci fi cati on of a cl ass path, i t seems to be i mportant to put any cl ass fi l es, for exampl e, db2java.zip for DB2 or classes111.zip for Oracl e, i n the system cl ass path. Before you start WebSphere Studi o make sure the necessary zi p/jar fi l es ar e i n the cl ass path (Control Panel ->System->Environment ->CLASSPATH). The next i mportant poi nt i s to speci fy wher e WebSpher e Studi o stores the publ i shed fi l es. Usual l y thi s i s the pl ace wher e the WebSphere Appl i cati on Server resi des. Unfor tunatel y one cannot change the pr efer ences wi thout havi ng a pr oject open. That i s the reason why we come back to thi s poi nt i n Publ i sh the Project on page 194. The exampl es descri bed her e ar e pr ovi ded as ar chi ve fi l es. To open them, sel ect File->Open Archivefr om the menu and sel ect the I tso.war fi l e fr om the Studiodi rectory. Repl ace the content of the I TSO pr oject wi th the extract of the I tso.war fi l e. Project Setup The devel opment of Web si tes i s or gani zed i n pr ojects i n WebSpher e Studi o. Natural l y the fi r st step i s to cr eate a new pr oject that wi l l be our pl ayground. When WebSphere Studi o i s star ted the fi rst ti me, i t asks whether i t shoul d cr eate a new pr oject, use an exi sti ng pr oject or exi t. We want to create a new project. So cl i ck Createnew i n the fi r st di al og (Fi gure 167). Figure167. CreateNew Project Now speci fy the name I TSO for the project (Fi gure 168). 182 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure168. Specify Project Parameters You shoul d now have a pr oject wi ndow (Fi gure 169). Figure169. WebSphereStudioProject Window Chapter 11. WebSphere Studio 183 Create an SQL Statement and Servlet To compose a database query and l et WebSphere Studi o create a servl et, we use the SQL Wi zar d: Sel ect the project I TSO on the l eft si de. Fr om the tool bar sel ect SQL Wizard (Fi gur e 170). Figure170. WebSphereStudioTool Bar I n the SQL Wi zar d di al og you have to provi de a name for the SQL statement. I n thi s exampl e we want to sel ect empl oyees and some data from thei r department from the database. The r ecor ds wi l l be sel ected by parti al empl oyee l ast names. Therefore we name the new SQL statement EmplDepByEmplName(Fi gur e 171). Figure171. Specify a Namefor theSQL Statement 184 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The next step i s to pr ovi de the wi zard wi th the necessary database connecti on i nformati on (Fi gure 172). As usual , we pr ovi de the fol l owi ng for DB2: Dr i ver: I BM DB2 UDB local (COM.ibm.db2.jdbc.app.DB2Driver) URL: jdbc:db2:itsowdb User I D and password: I TSO and itso (as i n al l exampl es) To cl ose the di al og, we cl i ck on Connect. Figure172. Specify theConnection Parameters Note: For Or acl e you woul d speci fy jdbc:oracle:thin:@localhost:1521:orcl for the database URL and Oraclefor the dr i ver. For SQL Ser ver you woul d speci fy jdbc:odbc:SQLServer for the database URL and J DBC-ODBC Bridgefor the dri ver. On the Tabl es page sel ect the two tabl es, depar tment and empl oyee, of the database (Fi gur e 173) and cl i ck Next. Chapter 11. WebSphere Studio 185 Figure173. Select Tables fromtheDatabase On the Joi n page, speci fy an i nner joi n by sel ecti ng DEPNO i n the department tabl e and WORKDEPT i n the empl oyee tabl e and cl i ck on J oin (Fi gure 174). Figure174. Specify theJ oin 186 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server On the Col umns page we sel ect the col umns to di spl ay (Fi gure 175). Duri ng the ti me thi s book was wr i tten, the data access bean seemed to have probl ems wi th date fi el ds (see Data Access Beans on page 266). To avoi d troubl e for the ti me bei ng, i t i s better not to sel ect a date fi el d. Figure175. Specify theColumns to Display On the Condi ti on 1 page we speci fy the condi ti on for the sel ect statement (Fi gure 176). Sel ect the EMPLOYEE tabl e, the LASTNAME col umn and the contains thecharacter(s) operator. Now we have to enter a host var i abl e for the val ue of the condi ti on. We cl i ck on the fi rst text fi el d and then on the Parameter button. A di al og to name the par ameter pops up and we enter lastName. Parameter val ues ar e di spl ayed i n bol d face i n the text fi el d wher eas fi xed val ues ar e di spl ated nor mal . Thi s speci fi cati on generates a WHERE cl ause of the for mat: LASTNAME LIKE '%'||?||'%' Chapter 11. WebSphere Studio 187 Figure176. Specify theConditions Because we do not want to sor t the output we can now vi ew the compl ete SQL statement (Fi gure 177) and then generate the code by cl i cki ng on the Finish button. Figure177. Completed SQL Statement The WebSpher e project wi ndow now contai ns a new fi l e named EmplDepByEmplName.sql. Thi s fi l e i s the basi s for the next step, that i s, to cr eate a ser vl et that accesses the database usi ng thi s SQL statement and to cr eate the cor respondi ng JavaServer Pages that provi de the i nput and output for the servl et. SELECT ITSO.EMPLOYEE.FIRSTNME, ITSO.EMPLOYEE.LASTNAME, ITSO.EMPLOYEE.PHONENO, ITSO.EMPLOYEE.JOB, ITSO.EMPLOYEE.SALARY, ITSO.DEPARTMENT.DEPTNAME FROM ITSO.DEPARTMENT, ITSO.EMPLOYEE WHERE ( (ITSO.EMPLOYEE.WORKDEPT = ITSO.DEPARTMENT.DEPTNO) AND (ITSO.EMPLOYEE.LASTNAME LIKE '%'||?||'%') ) 188 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Create the Servlet and JSPs The SQL query i s r eady and can be used i n the Database Wi zar d to cr eate a servl et and a JSPO. Sel ect the DatabaseWizard fr om the tool bar (Fi gure 170 on page 183) or fr om the menu. We onl y have one query so far, EmplDepByEmplName.sql. I t shoul d be sel ected by defaul t, i f not sel ect i t fr om the combobox (Fi gure 178). Cl i ck Next. Figure178. Select theSQL Statement The next step i s to sel ect what Web pages shoul d be created (Fi gur e 179). Because WebSpher e Studi o 3 beta 2 and WebSphere Appl i cati on ser ver 2.0.2 ar e a l i ttl e i nconsi stent at the moment, you shoul d not use the l ast opti on. For an expl anati on see WebSpher e Studi o on page 267. Cl i ck Next. Chapter 11. WebSphere Studio 189 Figure179. Select theGenerated Pages Now we speci fy the parameter s that wi l l appear on the i nput page. We need at l east the lastNamepar ameter (Fi gur e 180). Cl i ck Next. Figure180. Specify I nput Parameters 190 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Thi s next step i s si mi l ar, but speci fi es the par ameters for the resul ti ng output page (Fi gur e 181). We sel ect al l the tabl e col umns, but ar e not i nter ested i n the database dri ver, URL, SQL statement, and user I D, al though thi s mi ght be useful for testi ng purposes. Cl i ck on Next. Figure181. Specify theFields for theResult Page I n the next step you may add your own er ror message or you mi ght even speci fy your own err or page. We do not have our own err or handl i ng for now, and therefore we use the defaul t. The next step i s to sel ect whi ch methods of the generated JavaBean have to i nvoked and i n what order. Because we onl y have one method, the executemethod, we do not change anythi ng. The executemethod does the actual quer y. Now we may speci fy whether the quer y i s used i n more than one output page. I f so, thi s step enabl es us to attach the bean to an HttpSessi on object, whi ch i s then accessi bl e by more than just the di r ect JSP output page. I f mul ti pl e output pages are not sel ected, the resul ti ng bean i s just par t of the request object and i s onl y accessi bl e from the JSP r esul t page of the gener ated ser vl et. For thi s si mpl e exampl e we do not sel ect mul ti pl e output pages (Fi gur e 182). Chapter 11. WebSphere Studio 191 Figure182. Specify toUsetheBean in a Session The l ast step i s to gi ve mor e detai l ed i nformati on to the servl et generator regardi ng the Java package (itso.wasdb.studio) and the name of the fi l e. To provi de that i nformati on, cl i ck the Advanced button i n the Finish di al og and provi de the package name and the prefi x (Fi gur e 183). Figure183. ProvidePackageNameand Class NamePrefix The Finish di al og i s shown i n Fi gure 184. Cl i ck the Finish button. 192 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure184. Finish theWizard Project View after the Database Wizard The pr oject vi ew shoul d now show a few more fi l es (Fi gure 185). Figure185. Project after Servlet Generation Chapter 11. WebSphere Studio 193 Her e i s a descr i pti on of the newl y generated fi l es: Empl DepByEmpl Name.j ava and Empl DepByEmpl Name.cl ass are the Java sour ce and cl ass fi l es for the bean that represents the actual database query. The bean uses the I BM data access bean and the I BM connecti on manager to access the database. I t offers sever al methods; the most i mportant one i s the executemethod, whi ch per for ms the quer y. Moreover, for each output col umn sel ected i n Fi gure 181 on page 190, i t offer s a getCOLUMN_NAME method, whi ch returns the parti cul ar val ue for that col umn of the query. Empl Dep.j ava and Empl Dep.cl ass ar e the Java source and cl ass fi l es for the gener ated ser vl et. The ser vl et i s der i ved from the PageListServlet cl ass. That means the pages that ar e cal l ed fr om thi s servl et are not har d-coded, but speci fi ed i n the ser vl et confi gur ati on fi l e EmplDepServlet.servlet. The most i mpor tant method i s the performTask method. I t reads par ameters from the servl et confi gur ati on fi l e (user I D, password, database dr i ver, URL). I t al so r eads the i nput par ameters speci fi ed i n Fi gur e 180 on page 189 from the request, i ni ti al i zes the database bean EmplDepByEmplNamewi th the necessary par ameters, and i nvokes i ts execute method. Addi ti onal l y, i t adds the i nstance of the EmplDepByEmplNamebean to the request, then cal l s the output JavaSer ver Page. Empl DepServl et.servl et i s an XML-based confi gur ati on fi l e that sets the rul es for the ser vl et. I t r egul ates whi ch page i s to cal l when the ser vl et has successful l y accessed the database, and al so whi ch page i s to i nvoke i n case of an error or i n case no data was found. Fur ther mor e, i t contai ns key/val ue pai r s for the user I D, the password, the database dr i ver, and the URL. Empl DepI nputPage.html i s an HTML si mpl e i nput page that enabl es the user to enter a val ue for the lastNamepar ameter and then i nvokes the EmplDep ser vl et. Empl DepResul tPage.j sp i s the JavaServer Page that i s cal l ed fr om the servl et after successful l y accessi ng the database. To di spl ay the r esul ts i t uses the EmplDepByEmplNamebean that was i nstanti ated by the servl et and gi ven to thi s page thr ough the r equest bl ock. Empl DepErr orPage.j sp i s the JavaServer Page that i s cal l ed i n case of an err or. 194 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Publish the Project The fi nal step for thi s sampl e ser vl et i s to depl oy al l the gener ated fi l es to the WebSphere appl i cati on server, that i s, to publ i sh the fi l es to the server. We have to make sur e that WebSpher e Studi o publ i shes the fi l es to the proper di rectori es for the HTTP Ser ver and WebSphere. I f you have used a defaul t i nstal l ati on, WebSphere sear ches for servl ets under : c:\WebSphere\AppServer\servlets and the I BM HTTP Ser ver i s l ooki ng for HTML fi l es i n: c:\Program Files\IBM HTTP Server\htdocs Publishing Configurations There are thr ee possi bl e confi gurati ons between WebSphere Studi o and WebSphere Appl i cati on Ser ver : I n case WebSphere Studi o and the WebSphere Appl i cati on Server are on the same machi ne, we check that the publ i shi ng properti es of the ser ver are cor rect. We swi tch to the publ i shi ng vi ew i n the project wi ndow by sel ecti ng View ->Publishing, or al ter nati vel y by cl i cki ng the appropr i ate i con fr om the tool bar. Open the pr operti es from the context menu of the server (Fi gure 186). Figure186. Specify Publishing Options I n the properti es di al og, cl i ck on the Default Publishing Target button (Fi gure 187). Make sure the sur e the targets match your confi gur ati on. Chapter 11. WebSphere Studio 195 Figure187. Publishing Server Properties I n case WebSphere Studi o and the WebSphere Appl i cati on Server are on di ffer ent Wi ndows machi nes but the machi ne wi th the Appl i cati on Server i s accessi bl e as a shared dr i ve, the publ i shi ng i s al most the same, except for the fact that the ser ver name i s not localhost. You may speci fy thi s al so i n the ser ver properti es di al og (Fi gur e 187). I n case the WebSphere Appl i cati on Server i s on a machi ne that i s not accessi bl e as a shar ed dri ve, use an FTP upl oad mechani sm to publ i sh the fi l es to the appl i cati on ser ver. Agai n the ser ver pr oper ti es di al og (Fi gure 187) i s the pl ace to detai l the FTP par ameters. Once the publ i shi ng confi gurati on i s speci fi ed, we can publ i sh the fi l es to the Appl i cati on Server and the HTTP Ser ver. From the context menu of the server http://myserver sel ect Publish this Server. I n the fi rst di al og that i s di spl ayed you may speci fy addi ti onal opti ons. For our exampl e, no changes are requi red. I n the next di al og we can sel ect the fi l es to be publ i shed; the defaul t sel ecti on i s corr ect for thi s step as wel l . 196 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Assembly Stages WebSphere Studi o has two pr edefi ned assembl y stages, test and producti on. Sel ect View ->Assembly Stageto swi tch between the two stages. You can defi ne the test assembl y stage for l ocal publ i shi ng (l ocal host) and the producti on assembl y stage for publ i shi ng to another Web ser ver. Set up the properti es and publ i shi ng targets for both assembl y stages. Publishing Targets The publ i shi ng target di al og defi nes the two di r ectori es for publ i shi ng HTML/JSP fi l es and servl et cl asses (Fi gur e 188). Figure188. Publishing Targets Chapter 11. WebSphere Studio 197 Testing the Generated Servlet Testi ng i s easy and strai ghtfor ward once the project has been publ i shed to WebSphere. From the context menu of the EmplDepI nputPage.html fi l e sel ect Preview ->netscapeor iexploredependi ng on the favor i te browser (Fi gure 189). Figure189. Select PreviewfromtheContext Menu The HTML i nput page i s pl ai n but functi onal (Fi gure 190). Figure190. Generated HTML I nput Page 198 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The HTML output page that i s generated by the JSP di spl ays the r esul t of the si mpl e servl et (Fi gure 191). Figure191. Generated HTML Output Page Enhanced Insert Example I n the second exampl e we wi l l devel op a si mpl e ser vl et that i nserts a new empl oyee i n the database. Wi th the hel p of the Studi o Wi zards thi s i s al so a very si mpl e pr ocess. I n the second step we wi l l enri ch the i nput page of the i nser t ser vl et so that i t al r eady shows al l avai l abl e depar tment number s i n a combobox. Because the depar tment number i s a for ei gn key i n the empl oyee tabl e, thi s assur es that onl y exi sti ng val ues wi l l be i nser ted. Create an SQL Statement The fi r st step i s to create an SQL statement wi th the SQL Wi zard: Name the SQL statement I nsertEmployee. Provi de the connecti on par ameters. Sel ect the empl oyee tabl e and make sur e you sel ect I nsert for the SQL type (Fi gure 192). Chapter 11. WebSphere Studio 199 Figure192. Creating an I nsert Statement Sel ect the col umns that ar e i nserted. The col umns wi th the bl ue backgr ound ar e not nul l col umns i n the tabl e, therefore they are mandator y (Fi gure 193). I n addi ti on to the mandator y fi el ds we sel ect the PHONENO and the WORKDEPT fi el d. Figure193. Select theI nput Fields 200 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The r esul ti ng SQL statement i s shown i n Fi gur e 194. Figure194. Generated SQL I nsert Statement Create a Servlet Wi th the SQL statement speci fi ed, the next step i s to create a servl et based on that statement. We use the Database Wi zard: Sel ect the I nsertEmpl yee.sql statement that was just created. Create an i nput and resul t page. Sel ect the i nput fi el ds empNo, firstName, midI nit, lastName, edLevel, phoneNo, and workDept. You mi ght al so want to sor t them usi ng the up and down ar rows on the r i ght si de. Sel ect col umns for the r esul ts page, for exampl e firstNameand lastName. Sel ect the executeMethod i n the next step. We do not use the bean i n mor e than one page, so no change i s necessar y i n the next di al og. Fi nal l y speci fy the advanced par ameters, that i s, the package name itso.wasdb.studioand a meani ngful pr efi x, for exampl e I nsertEmpl. Cl i ck Finish to generate the code. Publ i sh the project. Viewing the Result The i nput page i s shown i n Fi gur e 195. Noti ce that the user i s al l owed to speci fy any worki ng depar tment number r egardl ess of whether the department exi sts or not. I t woul d be ni ce to enhance thi s pr ocess to al l ow the user to sel ect onl y exi sti ng department numbers. Thi s i s what we wi l l do next. INSERT INTO ITSO.EMPLOYEE ( EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, EDLEVEL ) VALUES ( ?, ?, ?, ?, ?, ?, ? ) Chapter 11. WebSphere Studio 201 Figure195. I nsert a NewEmployee Determine all Available Department Numbers To enhance the i nput for m wi th a combobox that di spl ays al l the avai l abl e department number s, we cr eate an SQL statement to retr i eve them. Thi s step i s qui te easy wi th the SQL Wi zar d: Create a new SQL statement named AllDepNumbers. Provi de the connecti on par ameters. Sel ect the department tabl e. Sel ect the DEPTNO col umn to i ncl ude (Fi gur e 196). That i s al l . Cl i ck Finish. 202 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure196. Select theDEPNO Column Based on thi s statement, we create a servl et usi ng the Database Wi zard. Al though we actual l y do not need i nput and output pages, we wi l l cr eate an output page because the PageListServlet cl ass apparentl y requi res i t. Later, when the ser vl et i s cr eated, we wi l l modi fy the sour ce sl i ghtl y, so that no output page i s cal l ed and we can al so del ete the output page. Conti nue to the sessi on step. Gi ve the bean a meani ngful name, for exampl e, change i t fr om BeanAlias to depNumbers. Conti nue to the end; no changes shoul d be necessar y. Speci fy as usual the package itso.wasdb.studioand the pr efi x AllDepNumbers, and fi ni sh the wi zar d. Invoke the Servlet from a JSP We want to use the ser vl et we just created as an i nput for the page where we speci fy the new empl oyee, that i s i n the I nsertEmplI nputPage.html. We use the HTML page as a base and modi fy i t and create a JSP fi l e. Open the page by doubl e cl i cki ng on i t. The WebSphere Studi o Page Desi gner i s star ted (Fi gure 197). Thi s i s the HTML/JSP edi tor of WebSphere Studi o. We wi l l not provi de an i ntroducti on i n the usage of thi s edi tor, but you can use i t to enhance the gener ated i nput and output pages. We wi l l use the edi tor to add the i nvocati on of a servl et, the AllDepNumbers servl et, and at the same ti me add the bean that i s cr eated by the AllDepNumbers servl et. Thi s pr ocess makes i t possi bl e to use the bean to cr eate a combobox that hol ds al l the possi bl e department numbers retr i eved by the database query. Chapter 11. WebSphere Studio 203 Figure197. WebSpherePageDesigner Star t by addi ng a ser vl et i nvocati on to the top of the page. Use the menu I nsert ->Servlet. I n the di al og speci fy the name of the ser vl et to be i nvoked, i n our case the AllDepNumbersServlet (Fi gure 198). Enter itso.wasdb.studio.AllDepNumbersServlet as the code attri bute. Figure198. Specify theServlet to beI nvoked 204 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Thi s speci fi cati on generates the code <SERVLET code="itso.wasdb.studio.AllDepNumbersServlet"> </SERVLET> The next step i s to i nsert the bean, al so at the top. Sel ect I nsert ->J SP Tags ->Bean Tag from the menu. The name of the bean i s depNumbers (the name we gave a few steps earl i er ) and the type of the bean i s itso.wasdb.studio.AllDepNumbersBean (Fi gur e 199). Figure199. Specify Bean Parameters Thi s speci fi cati on generates the code <BEAN name="depNumbers" type="itso.wasdb.studio.AllDepNumbersBean"> </BEAN> Del ete the l ast text fi el d (the worki ng depar tment) and substi tute i t wi th a combobox. The r esul t page shoul d now contai n one servl et tag, one bean tag, and a combobox i nstead of a text fi el d (Fi gure 200). Chapter 11. WebSphere Studio 205 Figure200. ResultingPage Next, you have to provi de the possi bl e val ues for the combobox that are dynami cal l y retr i eved by the AllDepNumbers servl et. Doubl e-cl i ck on the combobox and speci fy the name workDept i n the di al og. Thi s i s the name the text fi el d had when we speci fi ed i t wi th the database wi zard (Fi gur e 193 on page 199). I n the same di al og swi tch to the Dynamic pane. Thi s i s the pl ace to provi de the combobox wi th possi bl e val ues. To retr i eve the val ues dynami cal l y, we sel ect the Loop Property and cl i ck on Browse. Another di al og i s di spl ayed where we can br owse the avai l abl e properti es of al l the beans accessi bl e fr om thi s page (Fi gure 201). Br owse the depNumbers bean and sel ect the I TSO_DEPARTMENT_DEPTNO property. On the same page speci fy the I temPropertythat i s di spl ayed i n the combobox. I n thi s case i t i s the same as the l oop property (Fi gur e 201). Sel ect Specify as Property and br owse once mor e to the I TSO_DEPARTMENT_DEPTNO pr oper ty. I f we had speci fi ed mor e than one output fi el d i n the Database Wi zard (for exampl e, the department name), such fi el ds coul d al so be used her e. Servlet and Bean Combobox 206 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure201. SelectingtheLoop Property Swi tch to the Html Sourcevi ew and l ook at the gener ated code for thi s tabl e cel l (Fi gur e 202). The fi r st cel l of the tabl e r ow contai ns the word workDept. The next cel l contai ns the dynami c content that i s eval uated and repl aced by the WebSphere Appl i cati on Ser ver at r unti me. Basi cal l y, we speci fi ed whi ch property i s i ter ated and whi ch property i s di spl ayed as a val ue. I n our case, both ar e the same proper ty. Chapter 11. WebSphere Studio 207 Figure202. Generated Codefor Dynamic I temValues Ever ythi ng i s r eady. You mi ght want to enhance the l ook of the page. Al so, you mi ght want to i nspect the generated JSP and HTML code. Save the Modified HTML Page as a JSP Because we i mbedded Java l ogi c i nto the HTML page, we have to execute the page as a JSP. Save the page (File->SaveAs) as I nsertEmplI nputPage.jsp and sel ect Add to WebSphereStudioi n the save di al og. The Beta 2 pr oduct compl ai ns wi th an err or message that thi s i s not possi bl e and then asks you to save agai n. Just save agai n, and al though WebSpher e Studi o compl ai ned, everythi ng works fi ne. Modify the Generated Servlet The fi nal step i s to modi fy the gener ated source of the AllDepNumbers servl et. The servl et i s generated by WebSphere Studi o and by defaul t i t i s deri ved from the PageListServlet. A PageListServlet i s confi gur abl e by the matchi ng servl et XML confi gurati on fi l e (AllDepNumbersServlet.servlet). Thi s confi gur ati on fi l e contai ns some parameter s for the servl et, such as the database user I D, 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> 208 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server dri ver, and the URL. I t al so speci fi es whi ch output page i s the defaul t resul t page for the servl et, whi ch page i s the error page, and al l the other possi bl e output pages. I n our case, we do not want an output page cal l ed by the ser vl et. For thi s reason, we change the sour ce code of the servl et: Open the Java sour ce fi l e of the servl et, that i s, AllDepNumbers.java. I t has several methods; the most i mpor tant one i s the performTask method. At the very end of thi s method, you wi l l fi nd the fol l owi ng l i ne: callPage(getPageNameFromRequest(request), request, response); Comment i t out. The effect i s si mpl e. The output JSP page we had confi gur ed i s not cal l ed anymor e. Thi s i s exactl y what we woul d l i ke to achi eve, because the ser vl et i s al r eady cal l ed fr om a JSP and the output of the servl et i s the depNumbers bean, whi ch i s i ncl uded i n the output JSP. Save the fi l e and sel ect Compilefrom the context menu i n WebSpher e Studi o. Fi nal l y sel ect the server and publ i sh the pr oject to the server. Test the JSP and the Servlet in WebSphere After publ i shi ng the code to the WebSpere Appl i cati on Ser ver we can test the JSP and the servl et. Sel ect Preview ->iexploreor navigator fr om the context menu of the I nsertEmplI nputPage.jsp from the Publ i sh vi ew. As you can see i n the browser, the wor ki ng depar tment now contai ns a combobox wi th al l avai l abl e department number s (Fi gure 203). Problem with Servlet Configuration The JSP cal l s the AllDepNumbers ser vl et. When l oaded, the code l ooks for the servl et confi gur ati on fi l e, AllDepNumbers.servlet, but the gener ated fi l e i s named AllDepNumbersServlet.servlet. We copi ed the AllDepNumbersServlet.servlet fi l e as AllDepNumbers.servlet and depl oyed that copy i nto the same di rectory. Note: We al so tri ed to cal l the servl et by the name AllDepNumbersServlet (Fi gure 198 on page 203), but then the l oad of the servl et fr om the JSP servl et fai l ed compl etel y. Chapter 11. WebSphere Studio 209 Figure203. Enhanced I nsert Servlet I nput Pagewith Combobox 210 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Debugging the Servlets in VisualAge for Java Her e ar e the steps r equi r ed to debug the generated servl ets i n Vi sual Age for Java. As a pr erequi si te, the I TSOWDB database must be avai l abl e and accessi bl e through the same JDBC dri vers, URL, user I D, and passwor d as speci fed for WebSpher e. I mpor t the si x ser vl et sour ce and bean fi l es (.java) i nto the I TSO SG24 5471 project i n Vi sual Age for Java. The itso.wasdb.studiopackage i s cr eated. Err or messages ar e r epor ted for each ser vl et. import comm.ibm.webtools.runtime.*; <=== missing package Thi s package i s not requi red, therefore you can del ete the l i ne from each servl et. Copy the HTML and JSP fi l es to the proper HTML di r ectory. I f you performed a l ocal publ i shi ng, the fi l es shoul d be ther e al ready. Copy the servl et confi gurati on fi l es (.servl et) i nto the resour ces di r ectory: c:\IBMVjava\ide\project_resources\ITSO SG24 5471\itso\wasdb\studio Make sur e that you have the AllDepNumbers.servlet fi l e (copy of AllDepNumbersServlet.servlet). Star t the WebSpher e Test Envi ronment and open a br owser wi th the URL: http://127.0.0.1:8080/EmplDeptInputPage.html http://127.0.0.1:8080/InsertEmplnputPage.jsp You can set br eakpoi nts i n the ser vl et code to acti vate the debugger. Chapter 11. WebSphere Studio 211 Hints and Tips for WebSphere Studio The beta code of WebSphere Studi o has some pr obl ems that may di sturb smooth operati on. Her e ar e a few poi nter s on how to deal wi th pr obl ems. Synchronization between Development and Publishing View I t seems that someti mes fi l es of the devel opment vi ew (l eft si de of the project vi ew) do not show up i n the publ i shi ng vi ew (r i ght si de). The Sync left view and right view push button i n the tool bar does not work (Fi gure 204). You can force a fi l e to the publ i shi ng vi ew by sel ecti ng i t, open i ts properti es, and on the Publ i shi ng page desel ect the Set publishablecheckbox. Cl i ck OK. Then open the pr oper ti es agai n, sel ect the checkbox, and cl i ck OK. Thi s copi es the fi l e to the publ i shi ng vi ew. Checkout Fi l es that have been edi ted have the checkout fl ag (a red check mar k). You can sel ect the fi l e and sel ect Check I n fr om the context menu. I n the di rectory structure, checked out fi l es are i n the di r ectory: c:\WebSphere\StudioBeta\check_out\..projectname... Fi l es that are checked i n are marked r ead-onl y i n the di rectory: c:\WebSphere\StudioBeta\projects\..projectname... Publishing Warnings About Old Class Files When publ i shi ng, we got a warni ng message that the cl ass fi l e (.cl ass) was ol der than the source fi l e (.java). I n such si tuati ons you can check out the sour ce and cl ass fi l es and compi l e the source fi l e (sel ect Compilefr om the context menu). After that check both fi l es i n. Mismatch between Servlet and Servlet Configuration For a servl et cal l ed from a JSP, the nami ng of the servl et (.java) and ser vl et confi gur ati on fi l e (.ser vl et) does not wor k. See Pr obl em wi th Servl et Confi gurati on on page 208 for a ci rcumventi on. 212 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Project View Fi gur e 204 shows our pr oject vi ew after compl eti ng al l the sampl es. Figure204. CompleteProject View Copyright IBM Corp. 1999 213 12 WebSphere User Profile I n thi s chapter we descr i be the user pr ofi l e functi on of WebSpher e. We al so devel op a sampl e servl et uti l i zi ng the user profi l e functi on. 214 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Description The WebSpher e Appl i cati on Ser ver i ncl udes cl asses i n the com.ibm.servlet.personalization.userprofilepackage that make i t easi er to mai ntai n persi stent i nfor mati on about your Web si te vi si tor s and use that i nfor mati on to customi ze your Web pages. At the ti me of the rel ease of the WebSphere, the cl asses of the package com.ibm.servlet.personalization.userprofilear e consi der ed a reference i mpl ementati on, because i ssues, such as database schema and r unti me envi ronments, can var y gr eatl y from appl i cati on to appl i cati on. Gi ven these consi derati ons, WebSpher e i ncl udes the sour ce of the User Pr ofi l e cl ass and an exampl e of how to extend the cl ass. Both source fi l es ar e i n the WebSphere\AppServer\samples\userprofile di rector y. The onl y coupl i ng between the UserProfilecl ass and the rest of WebSpher e i s that the UserProfilecl ass and I BM's sessi on i mpl ementati on (I BMSessionData) have a user name fi el d that can be used to create some syner gy between the two cl asses. The User Profi l e cl ass i ncl udes data members for a vi si tor's compl ete name, postal and e-mai l addresses, and tel ephone numbers, and has fi el ds to store l anguage of choi ce, empl oyment, and user-defi ned group i nfor mati on. I n addi ti on, i t has a gener i c message, a shoppi ng car t, and a cl i pboar d that i s a Java hash tabl e. Thi s al l ows you to easi l y i ncor porate other objects of your choi ce i nto these data member s and handl e them as par t of the User Pr ofi l e cl ass. Because these objects are persi stent acr oss successi ve i nstanti ati ons of the UserPr ofi l e, they must be ser i al i zabl e. I f you use a JDBC database, the objects wi l l be stored i n the database. Otherwi se, they wi l l be stored as fi l es. I n the WebSphere Appl i cati on Ser ver Versi on 2.0, the UserProfilecl ass uses the database connecti on manager to mai ntai n JDBC connecti ons. Configuration To set up the user pr ofi l e functi on, you shoul d use WebSpheres admi ni str ati on di al ogs. Once you have star ted the admi ni strati on pr ogram (see WebSpher e Confi gur ati on on page 6), sel ect Setup ->UserProfile. Enable Page On the Enablepage sel ect yes for UsingUserProfile? (Fi gur e 205). As you can see the User Profi l e cl ass i tsel f can be modi fi ed. So i f your appl i cati on has some speci fi c needs where i t r equi r es modi fyi ng the code, you can do so and can pl ace the modi fi ed cl ass name i n here. Chapter 12. WebSphere User Profile 215 Figure205. Enabling User Profile Database Page The database i nfor mati on requi red here i s based on the URL used for the JDBC connecti on. Every database server has i ts own URL and each di ffer s from the other. The way i n whi ch the UserPr ofi l e uses the i nformati on i s as fol l ows: URL: jdbc:"+ Confi g.DBUSED + ":" + Confi g.DB_NAME; TableName: Confi g.DB_OWNER + "." + Confi g.USER_TABLE Fi gur e 206 shows the speci fi cati on for DB2, Fi gure 207 for Oracl e, and Fi gure 208 for SQL Server. 216 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server DB2 Figure206. UserProfileDatabaseSetup for DB2 Oracle Figure207. UserProfileDatabaseSetup for Oracle Chapter 12. WebSphere User Profile 217 SQL Server Figure208. UserProfileDatabaseSetup for SQL Server Connection Manager Page On the ConnMgr (connecti on manager ) page you sel ect the pool wi th respect to the database you have sel ected on the Databasepage (Fi gur e 209). Figure209. UserProfiles Connection Pool Selection 218 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Cl i ck on Saveand l og off. The changes for the user pr ofi l e onl y take effect when you stop the Web server and WebSpher e. Then restart the Web ser ver. The User Profi l e tabl e i s cr eated the fi r st ti me an attempt i s made to access the user pr ofi l e functi on. User Profile Create, Update and Retrieve I n thi s secti on we bri efl y descri be how to cr eate, update, and r etri eve the user profilefrom the database to provi de you wi th some under standi ng on how the user pr ofi l e wor ks. Create Creati ng the user profi l e usi ng new UserProfile() does not resul t i n wr i ti ng the user pr ofi l e i nto the database. To create an entry i n the database tabl e use insertToDatabase(UserProfileuserProf). When usi ng the insertToDatabasemethod, the UserProfilepassed to i t must al ready have the UserNamepr oper ty set up, because there i s no method for setti ng the UserName. Therefore you cannot cal l new UserProfile() and then pass the newl y created cl ass to the insertToDatabasemethod. The way to create a UserProfilewoul d be usi ng the stati c method addUserProfile. Thi s method has three vari ati ons, whi ch are: UserProfileaddUserProfile(String userName) I n thi s method the userNamei s di r ectl y passed, and the returned UserProfiledoes contai n the userName. You can set the rest of the parameter s usi ng the setter methods avai l abl e i n the UserPr ofi l e cl ass. UserProfileaddUserProfile(HttpSession httpSession) I n thi s method the sessi on object i s expected to have a par ameter cal l ed userNameof type String. Thi s can be done wi th a method cal l such as httpSession.putValue("userName",userName). Once the userNamei s extr acted fr om the sessi on, addUserProfile(userName) i s cal l ed to create a UserProfile. Fr om thi s poi nt on, other parameter s are extracted fr om the sessi on, i f any of them i s set, and the appropr i ate setter method i s cal l ed. Note:The extr acti on of par ameters fr om the sessi on and cal l i ng the setter methods i s done behi nd the scene. UserProfileaddUserProfile(HashTableclipboard) I n thi s method the hash tabl e object i s expected to have a parameter cal l ed userNameof type String. Thi s can be done wi th a method cal l such Chapter 12. WebSphere User Profile 219 as clipboard.put("userName",userName). Once the userNamei s extr acted, the addUserProfile(userName) i s cal l ed. After that poi nt, other parameter s are extr acted and the appropr i ate setter method i s cal l ed. Note: The extr acti on of parameter s fr om the hash tabl e and cal l i ng the setter methods i s done behi nd the scene. The second and thi rd methods are merel y wr appers functi ons that cal l the fi rst method. Update You can update al l of the fi el ds except the userNamei n a User Profi l e object: void updateUserProfile(HttpSession sess) I n thi s method the sessi on object i s expected to have a par ameter cal l ed userNameof type String. void updateUserProfile(Hashtableclipboard) I n thi s method the hash tabl e object i s expected to have a parameter cal l ed userNameof type String. Retrieve There are sever al ways to retr i eve a User Pr ofi l e object: UserProfileretrieveUserProfileByUserName(String userName) Based on the user Name the User Pr ofi l e i s r etur ned. UserProfileretrieveUserProfile(String type, String key) typei s the col umn name i n the User Profi l e tabl e and key i s the val ue of the col umn. Enumeration retrieveUserProfiles(String type, String key, Statement s) I n thi s method a statement i s assembl ed based on the typeand method returned. The r esul ts are 0 or mul ti pl e user profi l es r eturned through an Enumerati on object. There are sever al other methods i n the UserProfilecl ass that can be used to retr i eve the UserProfilebased on di ffer ent pr operti es, for exampl e, retrieveUserProfilesByLanguage. 220 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server UserProfile Example I n thi s exampl e we want to demonstr ate how the UserProfilei s cr eated and accessed. Al so the usage of a shoppi ng car t i n the UserProfilecontext i s di scussed. Classes and Methods I n thi s exampl e we have empl oyed JavaBean, JSP, and Servl et methodol ogi es. The package itso.wasdb.userprofilecontai ns the cl asses used i n thi s exampl e. The fol l owi ng i s the l i st of cl asses (Fi gure 210). Figure210. itsowasdb.userprofileClass Listing Item I temi s a JavaBean cl ass that i s passed as a shoppi ngCart object to a UserPr ofi l e. The pr oper ti es are: String item; /* name of the item */ String price; /* price of the item */ An I temBeanI nfocl ass i s gener ated by Vi sual Age for Java when the I tem cl ass i s created. UserCart UserCart i s a JavaBean cl ass that contai ns the basi c i nformati on used to cr eate a UserProfile. The properti es ar e: String language; String firstName; String midName; String lastName; String userName; A UserCartBeanI nfocl ass i s gener ated by Vi sual Age for Java when the UserCart cl ass i s created. Chapter 12. WebSphere User Profile 221 Note: The two cl asses I temand UserCart ar e si mpl e Java Bean cl asses wi th getter and setter methods. We wi l l not descri be these cl asses i n detai l because they do not need fur ther expl anati on. UserProfileCartServlet The UserProfileCartServlet cl ass handl es al l of the i ncomi ng r equests and outgoi ng responses. I t i s wi thi n thi s cl ass wher e al l of the tr ansacti ons take pl ace. Fi gure 211 shows the methods of the User Pr ofi l eCartServl et cl ass. Figure211. UserProfileCartServlet Methods Listing The User Profi l eCar tServl et cl ass manages the access to the user pr ofi l e. I t cr eates a user profi l e i f i t does not exi st and di spl ays the contents for an exi sti ng user profi l e. The content of the shoppi ng cart of the pr ofi l e i s modi fi abl e. Our cl ass i s a subcl ass of PageListServlet, whi ch i s a subcl ass of HttpServlet that can i nvoke JSPs (Fi gure 212). Figure212. UserProfileCartServlet Class Declaration The addUserShoppingCart method adds the shoppi ng car t object i nto the UserProfile(Fi gur e 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; } 222 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure213. UserProfileCartServlet addUserShoppingCart Method Note: I n our si mpl e exampl e, the shoppi ng car t contai ns onl y one i tem. To make thi s a true shoppi ng car t, you can pass a Vector that contai ns mul ti pl e objects. Any col l ecti on type of object can be pl aced her e as l ong as al l of the col l ecti on objects and the objects i nsi de of them ar e Serializable. The createUserProfilemethod checks to see i f the pr ofi l e al r eady exi sts under the speci fi ed UserName. I f not, i t wi l l create and update the UserProfile fi el ds. I f there i s a UserProfileunder the same UserNamei t thr ows an excepti on (Fi gure 214). Figure214. UserProfileCartServlet.createUserProfile The doGet method pr ocesses i ncomi ng HTTP GET r equests (Fi gur e 215). Figure215. 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); } Chapter 12. WebSphere User Profile 223 The doPost method pr ocesses i ncomi ng HTTP GET r equests (Fi gur e 216). Figure216. UserProfileCartServlet doPost Method The getParameter method r eads a parameter from the HTML or JSP fi l e and returns i t as a stri ng (Fi gure 217). Figure217. 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 required if ( (isParameterRequired) && (paramValue == null) ) throw new Exception("Parameter" + parameterName + "was not specified."); // Set the return to the default value if the parameter was not found if (paramValue == null) paramValue = defaultValue; return paramValue; } 224 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The itemCreateToOutputPagemethod takes car e of creati ng an i tem and addi ng i t to the UserPr ofi l es shoppi ng cart. Once the update i s done successful l y, the output page (a JSP) i s cal l ed to di spl ay UserProfileand i ts shoppi ng cart content (Fi gur e 218). Thi s method i s i nvoked when the Submit button fr om the I temCreatepage (Fi gur e 226 on page 229) i s cl i cked. Figure218. UserProfileCartServlet itemCreateToOutputPageMethod The performTask method pr ocesses i ncomi ng requests for i nformati on. I t checks from whi ch page the request has been made and, based on that i nfor mati on, cal l s the appr opr i ate method (Fi gure 219). I n case any of the methods cal l ed throw an excepti on, the handleError method i s cal l ed, whi ch i n turn l aunches the er ror output page (Fi gure 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 page callPage(getPageNameFromRequest(request), request, response); } Chapter 12. WebSphere User Profile 225 Figure219. 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 page UserCart 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 } 226 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The processLogin method (Fi gur e 220) i s cal l ed fr om the Logi n Page (Fi gure 229 on page 231). Dependi ng on whether the UserProfilewi th the UserName al r eady exi sts or not, i t cal l s the User Output page (Fi gure 231 on page 233) or UserCr eate page (Fi gur e 230 on page 232). Figure220. UserProfileCartServlet processLogin Method The retrieveUserProfilemethod attempts to retr i eve a UserProfilebased on the userNamepassed. I f the UserProfiledoes not exi st, i t r etur ns false, other wi se i t returns true(Fi gur e 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 exists userCart.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 cart itemInfo.setItem(tempItem.getItem()); itemInfo.setPrice(tempItem.getPrice()); } //default output page callPage(getPageNameFromRequest(request), request, response); }//endif else { // UserCreate page is called if it's a new user callPage("UserCreate", request, response); }//endelse } Chapter 12. WebSphere User Profile 227 Figure221. UserProfileCartServlet retrieveUserProfileMethod The userCreateToOutputPagemethod (Fi gure 222) i s cal l ed from the UserCr eate page (Fi gure 230 on page 232), i t takes the parameter s passed for the UserPr ofi l e fi el ds and then creates the User Profi l e. I t al so stor es the new i nfor mati on of the User Pr ofi l e i nsi de an HttpSessi on object so i t can be accessed fr om other pages (see the itemCreateToOutputPagemethod i n Fi gur e 218 on page 224). Figure222. UserProfileCartServlet userCreateToOutputPageMethod 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 created javax.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 page callPage(getPageNameFromRequest(request), request, response); } 228 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Output Result I n thi s secti on we wi l l step through a fl ow of HTML pages to demonstr ate the cr eati on or retr i eval of a user pr ofi l e starti ng from the l ogi n page. The Logi n page (Fi gur e 223) i s the fi r st page di spl ayed. After enter i ng the user name, contr ol passes to the next page, dependi ng on whether a user profi l e for the user name exi sts or not. Figure223. UserProfileLogin Page I f the user name enter ed i n the Logi n page does not exi st i n the User Pr ofi l e tabl e, the UserCr eate page (Fi gur e 224) i s cal l ed. Thi s page prompts you to cr eate a new User Profi l e. Figure224. UserProfileUserCreatePage Chapter 12. WebSphere User Profile 229 Once the user pr ofi l e i s cr eated, the resul t i s di spl ayed i n the defaul t output page (Fi gure 225). Figure225. UserProfileDefault OutputPageAfter User Registration You can create a new i tem to be added to the shoppi ng car t part of the UserPr ofi l e. The shoppi ng cart onl y takes one object. A new object al ways overwri tes the ol d one. Thi s i s done usi ng the I temCr eate page (Fi gur e 226). Figure226. UserProfileI temCreatePage After submi tti ng the i tem, the defaul t output page wi th the newl y created i tem i s di spl ayed (Fi gur e 227). 230 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure227. UserProfileDefault Output PageAfter I temCreation XML, HTML, and JSP Files I n thi s secti on we l i st al l the source fi l es that contr ol the servl et and the HTML output. The servl et knows fr om whi ch page a r equest i s i ni ti ated by l ooki ng at the val ue of the hi dden fi el d PageName. Thi s fi el d i s set i n al l JSP and HTML fi l es. XML Servlet Configuration File The UserProfileCartServlet.servlet fi l e (Fi gur e 228) i s an XML fi l e whi ch contai ns the defi ni ti on for al l of the pages cal l ed by callPagemethod. The pages l i sted i n the servlet fi l e ar e al l of type J avaServer Pages. Chapter 12. WebSphere User Profile 231 Figure228. UserProfileCartServlet.Servlet Control File Login HTML File The UserProfileLogin.html fi l e (Fi gur e 229) i s the fi r st page di spl ayed for the user l ogi n. Figure229. 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> 232 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server JSP Files The UserProfileCreate.jsp fi l e (Fi gure 230) contai ns the entry fi el ds for cr eati ng a new User Profi l e. Figure230. 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> Chapter 12. WebSphere User Profile 233 Noti ce the BEAN tag that r efer s to the UserCart JavaBean. The I NSERT tag retr i eves the userNameproperty fr om the bean. The UserProfileCartOutputPage.jsp Fi l e (Fi gur e 231) di spl ays the content of the UserPr ofi l e, i ncl udi ng the contents of i ts shoppi ng cart. Figure231. UserProfileCartOutputPage.jsp File I n thi s JSP fi l e the userCart i s defi ned i n a BEAN tag and i ts pr oper ty val ues are retr i eved i n I NSERT tags. The I temI nfoI nputPage.jsp fi l e (Fi gure 232) contai ns the entr y fi el ds for cr eati ng a new I tem. <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> 234 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure232. I temI nfoI nputPage.jsp File The UserProfileCartErrorPage.jsp fi l e (Fi gure 233) contai ns a message for the err or. The detai l of the err or i s l oaded i nto the page dynami cal l y (Fi gure 219 on page 225). Figure233. 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> Chapter 12. WebSphere User Profile 235 Testing the User Profile Sample in VisualAge for Java The user profi l e sampl e wi l l fai l i n the Vi sual Age for Java test envi ronment because no database i nfor mati on has been pr epar ed for stor i ng user profi l es. Setting up the Database To acti vate the user pr ofi l e functi on we have to change a properti es fi l e of the WebSphere Test Envi ronment: c:\IBMVJava\ide\project_resources\IBM WebSphere Test Environment\ properties\server\servlet\servletservice\userprofile.properties Change the properti es fi l es as shown i n Fi gur e 234. Figure234. User Profiles Properties File Source Files The source fi l es must be pl aced i nto appr opri ate di rectori es: UserProfileCartServlet.servlet: store i n the project r esour ces di rectory of Vi sual Age for Java: c:\IBMVJava\ide\project_resources\ITSO SG24 5471\itso\wasdb\userprofile UserProfileLogin.html: stor e i n a subdi rectory of the HTML di rector y: c:\Program Files\IBM HTTP Server\htdocs\itso J SP Files: stor e i n a subdi rectory of the HTML di rector y: c:\Program Files\IBM HTTP Server\htdocs\itso\jsp # @(#)userprofile.properties # # User Profiles Configuration Screen # ncf.userprofile=true ncf.userprofile.db.used=db2 ncf.userprofile.db.jdbcdriver=COM.ibm.db2.jdbc.app.DB2Driver ncf.userprofile.db.instance=ITSOWDB ncf.userprofile.db.owner=ITSO ncf.userprofile.tablename=userprofile ncf.userprofile.userid=ITSO ncf.userprofile.password=itso ncf.userprofile.classname=com.ibm.servlet.personalization.userprofile.UserProfile # # Properties for connection manager initialization ncf.userprofile.connmgr.poolname=JdbcDb2 ncf.userprofile.connmgr.waitretry=false 236 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Run the User Profile Sample Star t the WebSpher e Test Envi ronment and open a br owser wi th the URL: http://127.0.0.1:8080/itso/UserProfileLogin.html The fi r st access to a user profi l e cr eates the I TSO.USERPROFI LE tabl e i n the I TSOWDB database. The output of the user pr ofi l e sampl e shoul d match the decr i pti on i n Output Resul t on page 228. Running the User Profile Sample in WebSphere Confi gure WebSphere as descri bed i n Confi gur ati on on page 214. Depl oy the beans and the ser vl et to WebSpher e: c:\WebSphere\AppServer\servlets The source fi l es must be pl aced i nto appr opri ate di rectori es: UserProfileCartServlet.servlet: store i n the servl ets di rector y of WebSphere, together wi th the servl et code and the beans. c:\WebSphere\AppServer\servlets\itso\wasdb\userprofile UserProfileLogin.html: stor e i n a subdi rectory of the HTML di rector y: c:\Program Files\IBM HTTP Server\htdocs\itso J SP Files: stor e i n a subdi rectory of the HTML di rector y: c:\Program Files\IBM HTTP Server\htdocs\itso\jsp Open a browser wi th the URL: http://hostname/itso/UserProfileLogin.html The fi r st access to a user profi l e cr eates the I TSO.USERPROFI LE tabl e i n the I TSOWDB database on the WebSpher e ser ver machi ne. The output of the user profi l e sampl e shoul d match the descr i pti on i n Output Resul t on page 228. Copyright IBM Corp. 1999 237 13 WebSphere Security and the LDAP Directory I n thi s chapter we di scuss secur i ng access to r esources usi ng a di rector y servi ce. 238 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Introduction A di r ector y servi ce i s a combi nati on of: An information repository: A database i s often used to stor e l ocati on i nfor mati on and other detai l s about resources such as users, pri nters, fi l e servers, and appl i cati on server s. An access method: The Li ghtwei ght Di r ector y Access Pr otocol (LDAP) or other access methods can be used to communi cate wi th di r ector y servi ce components. Related services: A di rector y servi ce provi des faci l i ti es for quer yi ng, mani pul ati ng, and authenti cati ng the i nformati on i n i ts database. You mi ght al ready have set up a di rector y servi ce product to hol d gl obal securi ty data that many other softwar e appl i cati ons, such as an appl i cati on server and your Web ser ver, can use to authenti cate users who tr y to access resources. WebSphere supports the use of thr ee di fferent di r ector y servi ce types: Domi no 4.6 Netscape Di r ector y Server e-Network I BM Sui te The secur i ty access to the di rectory ser vi ce i s pr ovi ded through ACL, access control list, i n WebSphere. When usi ng di rectory ser vi ce for secur i ty, WebSphere acts as the cl i ent of the di rectory ser vi ce. The setup for the resource secur i ty i s done through an ACL. Resources such as servl ets are assi gned an ACL, and based on the permi ssi ons provi ded through the ACL, the l evel of access i s provi ded. Access Control Lists The ACL associ ated wi th a r esour ce speci fi es whi ch user s or gr oups i n a real m ar e per mi tted to access the r esour ce. ACLs, r eal ms, and resources have the fol l owi ng r el ati onshi ps (Fi gur e 235): A r eal m can contai n many ACLs. A r eal m can contai n many r esources. An ACL can bel ong to onl y one real m. A r esour ce i s associ ated wi th onl y one ACL. A r esour ce can bel ong to onl y one r eal m. An ACL can be associ ated wi th many resources. Chapter 13. WebSphere Security and the LDAP Directory 239 Figure235. Relationships Between Realm, ACL, and Resource I n some cases, a ser vi ce does not requi re i ts customers to be i n an access control l i st. For exampl e, many Web page (HTTP) ser vi ces make thei r documents avai l abl e to al l user s wi thout requi ri ng them to r egi ster i n an access control l i st (ACL). Realms A real m i s a database of users, gr oups, and ACLs. A user must be defi ned i n a real m i n order to access any r esour ces bel ongi ng to that r eal m. A user can bel ong to several r eal ms, but a user I D cannot be dupl i cated wi thi n a real m. For exampl e, the user amy can bel ong to the r eal ms fileRealmand anyRealm. Each of those r eal ms can contai n onl y one user named amy. The user amy can be gi ven di ffer ent per mi ssi ons for di ffer ent resources i n each real m. A per son, such as Amy, mi ght have di fferent user I Ds i n each r eal m. For exampl e, she mi ght be amy i n the fi l eReal m, but i s amy2 i n the anyReal m because there i s al r eady a person i n anyReal m usi ng the user I D amy. I BM WebSpher e Appl i cati on Ser ver shi ps wi th some pre-establ i shed real ms: The defaultRealmdefi nes how users may access r esources defi ned l ocal l y. You can establ i sh ACLs to determi ne whi ch users and gr oups have access to whi ch resources. The NT realmand the UNIX realmdefi ne how user s wi th accounts on your oper ati ng systems may access WebSphere resources. Users defi ned i n the operati ng system are shar ed by WebSphere and conti nue to exi st for as l ong as they exi st i n the under l yi ng system. The appl i cati on server manager i nter face l ets you vi ew thi s real m; to change i t, you must use the faci l i ti es provi ded by your operati ng system. Curr entl y, WebSphere can share user s, but not groups, defi ned i n the oper ati ng system. Realm ACL Resource 1 1 m 1 m m m = many 240 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The servletMgrRealmdefi nes how ser vl ets may access resources defi ned r emotel y, such as remotel y l oaded servl ets. The ser vl et ACL i s the onl y access contr ol l i st i n thi s r eal m. When a remotel y l oaded, di gi tal l y-si gned servl et tr i es to access a pr otected r esour ce, the di gi tal cer ti fi cate i n the ser vl et i s compar ed wi th di gi tal certi fi cates associ ated wi th user s i n the servl etMgr Real m. The servl etACL deci des whether permi ssi on i s granted or deni ed. For exampl e, suppose the di gi tal certi fi cate of userX i s packaged i n the anyServl et.JAR fi l e. I f user X i s added to the servl etMgrReal m, any ser vl et contai ni ng the same di gi tal certi fi cate as that of user X (found i n anyServl et.JAR) may execute and access resources granted to user X. Fi nal l y, the ldapRealm(Fi gur e 240 on page 244) i s di spl ayed i f you have a di rector y servi ce enabl ed on the Di r ectory Management page (Fi gure 236 on page 241) of the WebSpher e Appl i cati on Ser ver Admi ni str ati on. Users and groups defi ned i n the di rectory ser vi ce ar e shared by WebSphere and conti nue to exi st for as l ong as they exi st i n the di r ector y ser vi ce or unti l you di sabl e di r ectory management support. The appl i cati on ser ver manager i nter face l ets you vi ew thi s real m; to change i t, you must use the faci l i ti es the LDAP ser ver pr ovi des. For mor e i nformati on about LDAP, di r ector y servi ces, and the l dapReal m, see Usinga directory servicewith Application Server i n the WebSpher e onl i ne documentati on. Al so refer to the LDAP I mplementation Cookbook, SG24-5110. Resources Resour ces ar e the val uabl e i tems accessi bl e by the Web ser ver : HTML fi l es and di rectori es, such as http://www.anycompany.com Other fi l es and di rector i es, such as ftp://www.anycompany.com Web appl i cati ons: Java servl ets or CGI pr ograms and by the WebSphere Appl i cati on Server : Java servl ets Connecti ons, sockets, fi l es, and other r esources used by servl ets Custom ser vl ets that enabl e access to enterpr i se resour ces and appl i cati ons (such as databases) Each r esour ce can be protected by establ i shi ng a si ngl e ACL for that resource, i n a si ngl e r eal m. The ACL speci fi es whi ch user s or groups are al l owed to access or modi fy the r esource. Chapter 13. WebSphere Security and the LDAP Directory 241 For each r esour ce to pr otect, you speci fy: An access control l i st (ACL)a l i st defi ni ng who can use the r esour ce A secur i ty r eal ma l ogi cal securi ty area the resource bel ongs to An authenti cati on schemea way to veri fy users who ask for the resource The r el ati onshi p among these i tems wi l l become apparent shortl y. Setup and Configuration You must have i nstal l ed a di rectory ser ver and user I Ds cr eated for the di rectory ser ver pri or to starti ng the setup on WebSphere. Netscape Di r ector y Server 4.0 was used to pr ovi de secur i ty access to our resources, namel y ser vl ets. The fol l owi ng ar e the steps i nvol ved i n setup and confi gurati on of securi ty thr ough di rector y servi ce. Star t the WebSpher e Admi ni str ati on panel , see WebSpher e Confi gurati on on page 6. Sel ect Directory Management (Fi gur e 236). Figure236. WebSphereAdministration Setup for Directory Management Fr om the WebSphere Admi ni strati on mai n menu, sel ect the Access Control List and sel ect the ldapRealmand cl i ck on the Add button (Fi gur e 237). 242 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure237. WebSphereAccess Control List Main Panel Fr om the Add ACL panel , i nput the New ACL Name(Fi gure 238). Figure238. Adding a New Access Control List Fr om the Access Control Li st mai n panel (Fi gur e 237) sel ect the newl y cr eated ACL and cl i ck on the l ower Add button to add per mi ssi ons to the new ACL. Sel ect the type of per mi ssi ons you want to gi ve to a user or a gr oup (Fi gure 239). As you may have noti ced, the user I Ds and group I Ds are the same as the ones you have speci fi ed i n the di r ectory ser vi ce. Chapter 13. WebSphere Security and the LDAP Directory 243 Note: To enabl e access to the ser vl ets, you shoul d Assign Permission for Files and Folders. Files and Folders r efer s to l ocal di r ector i es and fi l es, i ncl udi ng servl ets. Servlets refers to remotel y l oaded ser vl ets. I f you ar e unsure whi ch to choose, Files and Folders i s the appr opri ate choi ce i n most cases. Figure239. Add Permission toACL At thi s poi nt you have speci fi ed your ACL, and the ACL panel di spl ays i nfor mati on based on the choi ces you made i n the Add Permission toACL panel (Fi gure 240). 244 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Figure240. WebSphereAccess Control List Main Panel with New ACL Next i s to set up access to your resources based on the newl y cr eated ACL. Sel ect Resources from the WebSpher e Admi ni str ati on mai n menu. From the Resources panel sel ect the ldapRealm. Cl i ck on the Add button to add a resour ce to the desi red ACL (Fi gure 241). Figure241. WebSphereResources Security Setup Chapter 13. WebSphere Security and the LDAP Directory 245 Fr om the Protect a Resourcedi al og, sel ect a Scheme, ACL, and a Resource to Protect, and cl i ck on the OK button (Fi gur e 242). Figure242. Protect a Resourceusing Directory Servicethrough ACL After per formi ng these steps you have speci fi ed your resource secur i ty access based on the setti ng i n the di rectory ser vi ce (Fi gur e 243). Figure243. ResourcePanel after Addinga Resourceto beProtected 246 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 247 14 Using SQLJ to Access a Database SQLJ i s a method of accessi ng database i nfor mati on usi ng embedded SQL i n Java code. I n thi s chapter we wi l l di scuss what you need i n order to use SQLJ and gi ve a si mpl e exampl e of usi ng SQLJ wi th WebSphere and DB2. Note: To use the SQLJ functi onal i ty, you must i nstal l fi xpack 8 for DB2 Versi on 5. 248 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server What is SQLJ? SQLJ al l ows Java progr ammers to cr eate stati c SQL for Java appl i cati ons as wel l as the dynami c SQL whi ch tr adi ti onal JDBC dri ver s pr ovi de. The use of stati c SQL al l ows al l author i ty, syntax, access strategy, and l ogi c checki ng to be done at SQL compi l e ti me. Thi s uni que abi l i ty pr ovi des per for mance i ncreases for appl i cati ons that repeatedl y use the same SQL. SQLJ was devel oped as a combi ned effor t by Oracl e, Tandem, and I BM to add stati c SQL to JDBC. I t has recentl y become an ANSI standar d. The speci fi cati on consi sts of three par ts: Par t 0 speci fi es the SQLJ l anguage syntax and semanti cs for embedded SQL statements i n a Java appl i cati on. Par t 1 speci fi es extensi ons that defi ne: I nstal l ati on of Java cl asses i n an SQL database I nvocati on of stati c methods as stored procedures Par t 2 speci fi es extensi ons for accessi ng Java cl asses as SQL di sti nct types. Most database vendors have i mpl emented part 0 of thi s pl an, but the goal i s to gradual l y i ntroduce the SQLJ technol ogy i nto the products. We focus onl y on part 0 i n thi s book. SQLJ and VisualAge for Java Unfortunatel y, Vi sual Age for Java 2.0 does not suppor t SQLJ. SQLJ oper abi l i ty i s schedul ed for Versi on 3, whi ch shoul d be avai l abl e i n the thi r d quarter of 1999. Vi sual Age for Java Versi on 2 cannot be used wi th SQLJ because Vi sual Age does not r ecogni ze the pr ecompi l er di recti ves that SQLJ uses before i ts transl ati on. Thi s i mpl i es that the embedded SQL statements and other SQLJ resources wi l l cause er ror s wi thi n Vi sual Age for Java. Thi s wi l l cause some devel opment sl owdown, because you cannot use the WebSphere Test Envi ronment and the Vi sual Age for Java debugger. Chapter 14. Using SQLJ to Access a Database 249 SQLJ Translators, Input, and Output To compi l e Java code wi th embedded SQLJ, you must put your code thr ough a transl ator that wi l l comment out and prepr ocess the SQLJ code so that a nor mal Java compi l er can successful l y compi l e the code. The nami ng conventi on for SQLJ states that al l Java fi l es wi th embedded SQLJ shoul d have an extensi on of .sqlj befor e they are transl ated. The SQLJ transl ator i s used to tr ansl ate .sqlj fi l es i nto .java fi l es. I t comments out al l of the SQLJ code and repl aces i t wi th the proper Java code used to i mpl ement the stati c SQL. When thi s tr ansl ati on occurs, Java cl asses are cr eated for the SQLJ i terators. I terator s are cursor s that ar e used to stor e the r esul ts of the embedded SQL quer y. Because the resul t sets can have di ffer ent number s of col umns and col umn types, a separ ate i terator must be created for each uni que resul t set. You defi ne a cursor to par se a r esul t set usi ng embedded SQL that i s l ater i nter preted by the transl ator. A cl ass and a seri al i zed fi l e are al so created for the quer y profi l e. Thi s profi l e mai ntai ns the data used to keep the SQL stati c. Updating Serialized Profiles I nstead of havi ng to rebui l d i nformati on as dynami c SQL does, the ser i al i zed profi l e stores the i nfor mati on necessar y to make the SQL executi on perform as qui ck as possi bl e. The ser i al i zati on fi l e stor es the bi nd i nformati on used to access the database. Thi s profi l e can be customi zed by runni ng i t through a customi zer whi ch connects to the database and updates the i nfor mati on stor ed r egardi ng accessi ng your data. Thi s customi zer i s found i n the same di rectory as the transl ator. For DB2 the customi zer i s cal l ed db2profc.exe. I t has the fol l owi ng usage: db2profc -user=<user> -password=<password> url=<database url> <profile name>.ser You shoul d customi ze the pr ofi l e when the tabl es si gni fi cantl y change i n vol ume. Fai l ure to do so can cause i neffi ci ent access methods to be used to access the data. Thi s i s i mportant, consi der i ng that per formance i s the mai n poi nt of usi ng stati c SQL fi l es. 250 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server DB2 Resources for SQLJ For appl i cati ons wr i tten usi ng SQLJ to work pr oper l y, certai n r esour ces must be avai l abl e. I t i s i mper ati ve that you i ncl ude the fol l owi ng fi l es i n your cl ass path. These fi l es must be i n the WebSpher e cl ass path as wel l . c:\sqllib\java\db2java.zip c:\sqllib\java\runtime.zip c:\sqllib\java\sqlj.zip The sqlj.zip fi l e i s i ncl uded wi th the DB2 Softwar e Devel oper s Ki t. I t pl aces the zi p fi l e i n the same di r ectory as other DB2 Java resources. SQLJ i s i mpl emented usi ng a JDBC connecti on to the database on Wi ndows NT. To execute the SQL, you must fi r st cr eate a connecti on and a connecti on context as shown i n our exampl e. Using the SQLJ Translator with DB2 Wi th the i nstal l ati on of DB2 Softwar e Devel oper s Ki t, an executabl e named sqlj.exei s pl aced i nto the d:\ sqllib\ bin di r ectory (where sql l i b i s the DB2 i nstal l ati on di rector y). Thi s fi l e i s the SQLJ tr ansl ator. The SQLJ command has the for mat: sqlj <Java file name with SQLJ> The output fi l e of type .java can be used by any Java tr ansl ator and can be compi l ed normal l y. The SQLJ tr ansl ator, by defaul t, automati cal l y compi l es the output fi l e and cr eates a seri al i zed profi l e. The tr ansl ator does not catch err or s i n the Java sour ce fi l e, so make sure the fi l e i s syntacti cal l y corr ect. Employees in Department Example We use our exampl e of fi ndi ng al l the empl oyees i n a speci fi c department. We i mpl ement thi s exampl e usi ng a ser vl et and a bean. The ser vl et contai ns al l the Java code to communi cate wi th the bean. The bean contr ol s the retr i eval and di spl ayi ng of the data. Chapter 14. Using SQLJ to Access a Database 251 Servlet The SqljServ ser vl et (Fi gur e 244) contai ns no SQLJ code, ther efor e i t i s not run thr ough the SQLJ transl ator. The servl et code i nvokes methods that contai n SQLJ through the SQLJ ServBean. Figure244. SQLJ ExampleServlet (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(); } } } } 252 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Bean with SQLJ Code Before Translation The SQLJ ServBean (Fi gure 245 and Fi gur e 246) cr eates the connecti on, executes the SQL, and di spl ays the resul t. These fi gures show the .sqlj code befor e transl ati on. Figure245. SQLJ ExampleServlet 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; } } } Chapter 14. Using SQLJ to Access a Database 253 The startconnection method creates a connecti on to the database and creates a defaul t context. SQLJ uses the defaul t context connecti on i n use wi th i ts seri al i zed pr ofi l e, so you must set one i n your code. Figure246. SQLJ ExampleServlet Bean (SqljServBean.sqlj) Part 2 public void executeSQLJ(PrintWriter out, String dep) throws SQLException { DataCursor cursor1;
long count1 = 0;
// retrieve data from the database System.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>"); } 254 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server The executeSQLJ method contai ns the embedded SQL. I t cr eates a cur sor to stor e the r esul t of the SQL query and r etur ns the resul t set to the cur sor. The outputI nfo method di spl ays the i nformati on contai ned i n the cursor. I t uses the PrintWriter cl ass to wr i te the r esul ts to the Web br owser. You can see how si mpl e i t i s to retr i eve a data i tem from the resul t set by the use of the cursor methods. SQLJ Code After Translation The SQLJ code i n these l i sti ngs performs mul ti pl e functi ons. Each i s descr i bed here and the Java code r esul ti ng from tr ansl ati on i s shown. Iterator #sql iterator DataCursor (String empno, String lastname, String workdept, String Sex) Thi s statement cr eates the i terator, or cursor, used to store the resul t set of the SQL quer y. Because the SQL can r etur n var yi ng col umns and types, we need to defi ne an i terator before i ncl udi ng what ki nd of output to expect so i t can pr oper l y store the i nformati on. The cur sor data types and the data types returned from the SQL statement are compared and checked duri ng the transl ati on of the SQLJ code. I n Fi gur e 247, we see the defi ni ti on of the i terator. The SQLJ transl ator cr eates thi s code, whi ch makes i t extremel y easy to manage the output of quer i es. You just cal l the method named after the col umn to retr i eve the i nfor mati on stor ed i n that col umn. The rows are traver sed usi ng the i terators next method as shown i n the outputI nfo method (Fi gur e 246 on page 253). Chapter 14. Using SQLJ to Access a Database 255 Figure247. SQLJ Codeafter Translation: I terator Class Definition /*@lineinfo:generated-code*//*@lineinfo:10^1*/ // ************************************************************ // SQLJ iterator declaration: // ************************************************************ class DataCursor extends sqlj.runtime.ref.ResultSetIterImpl implements 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*/ 256 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Select Statement with Result Set #sql cursor1 = { SELECT empno, lastname, workdept, sex from itso.employee where WORKDEPT = :dep }; Thi s sel ect statement i s embedded SQL code that uses a host var i abl e (:dep). You can see how si mpl e i t i s to use the SQL and return the r esul t i nto the i terator. Fi gur e 248 shows the tr ansl ated SQLJ code. I t i s chal l engi ng to under stand thi s code, but noti ce the use of the connecti on context. Thi s i s why i t i s necessary to cr eate a defaul t connecti on context when you cr eate your i ni ti al connecti on to the database. Al so noti ce how the code uses the Profi l eKeys. Profi l eKeys ar e an i ndex to al l the pr ofi l es used i n the appl i cati on and are stored i n the ser i al i zed fi l es that al l ow SQLJ to be stati c. Figure248. SQLJ Codeafter Translation: SimpleSelect 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*/ Chapter 14. Using SQLJ to Access a Database 257 Select Statement without Result Set #sql { SELECT count(*) into :count1 from employee where workdept = :dep }; Thi s statement does not return a resul t set, so i t does not r equi r e an i ter ator. I nstead, thi s set si mpl y counts the number of el ements i n the r esul t and stor es that number i n a host vari abl e (:count1). Fi gure 249 shows the transl ati on of thi s statement. Figure249. SQLJ Codeafter 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*/ 258 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Deployment of an SQLJ Servlet to WebSphere Movi ng the SQLJ ser vl et i s rel ati vel y si mpl e. Pl ace the servl et fi l es i n the same di rector y as the other ser vl ets on your machi ne. I t i s i mpor tant that you remember to move al l of the cl ass fi l es that are output fr om the transl ator. Any i ter ators you had wi l l create thei r own cl ass fi l e. A Pr ofi l eKey cl ass, whi ch i s an i ndex to your pr ofi l es, and the actual l y pr ofi l e (.ser fi l e) wi l l al so be created and must be accessi bl e by the ser vl et. The ser vl et di rectory contai ni ng your cl asses i s a natur al pl ace to put both of these fi l es. You shoul d al so make sur e that the proper cl ass paths ar e l i sted i n the Java Engi ne setup (Fi gure 250). You must be sur e to add the fi l es: c:\sqllib\java\db2java.zip c:\sqllib\java\runtime.zip c:\sqllib\java\sqlj.zip Figure250. WebSphereApplication Server: J ava EngineSetup Chapter 14. Using SQLJ to Access a Database 259 SQLJ Servlet Output The servl et i s now r eady to r un under WebSphere. The output i s shown i n Fi gur e 251. Figure251. Output of SQLJ Servlet Employees in Department Example 260 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 261 Appendixes 262 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 263 A Odds and Ends I n thi s chapter we descr i be the var i ous odds and ends that we encounter ed whi l e wor ki ng wi th the di fferent database systems. 264 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Different Mapping of SQL Types After cr eati ng the database and i nspecti ng i t wi th the tool s to bui l d query statements, we di scovered that the databases di ffer i n the way they i nter pret types. To see thi s, i t i s suffi ci ent to compar e the mappi ng of the empl oyee tabl e for DB2 (Fi gure 252), Or acl e (Fi gur e 253), and SQL Ser ver (Fi gur e 254). As you can see, mappi ng di ffers i n those fi el ds r el ated to dates and to the SMALLI NT fi el d. Unfor tunatel y, thi s makes i t i mpossi bl e to use one meta data speci fi cati on for the data access bean for al l databases. Thi s appl i es to code that depends on the I BM data access beans, that i s code gener ated by the Studi o Wi zar ds, code gener ated by the SmartGui des of Vi sual Age for Java when usi ng the Sel ect bean, and al so non-gener ated hand wr i tten code. Figure252. Default Mappingfor theEmployeeTablein DB2 Appendix A. Odds and Ends 265 Figure253. Default Mappingfor theEmployeeTablein Oracle Figure254. Default Mappingfor theEmployeein ODBC/ SqlServer 266 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Correct Deployment of Enterprise Beans Because the depl oyment of enter pr i se beans i s a somewhat di ffi cul t step, especi al l y because ver y few er ror messages ar e thrown that coul d i ndi cate what was wrong, keep the fol l owi ng r ul es i n mi nd: For a BMP bean, depl oy the EJS fi l e rather than the EJB fi l e i n Vi sual Age for Java. Thi s pr eserves the mappi ng to the database. I n WebSpher e, do not regener ate the bean, onl y redepl oy i t. Del ete any unused contai ners (Enti ty and Sessi on). Sessi on contai ners must speci fy a val i d DB2 database; al so veri fy that the speci fi ed user I D may access the database. To compl ete the depl oyment pr ocess, you have to stop WebSphere, then stop the HTTP Ser ver, and fi nal l y start the HTTP Server agai n, whi ch shoul d star t up the WebSphere Servl et Servi ce as wel l . Add memory to your computer; to use Vi sual Age for Java and WebSpher e we suggest 128MB mi ni mum. Data Access Beans I t seems that the data access beans do gener al l y wor k better when the i nput and output types are not speci fi ed usi ng cl asses, but usi ng i nteger val ues of the java.sql.Types cl ass. Unfortunatel y, thi s cr eates probl ems wi th the Wi zar ds of WebSpher e Studi o, because they al ways generate Cl assName.cl ass i nstead of Types.TYPE. Accordi ng to I BM support, thi s i s a known bug and i s fi xed as of ver si on 1.1 of the data access beans. Unfortunatel y thi s versi on i s nei ther par t of WebSphere nor WebSpher e Studi o. Especi al l y for WebSpher e Studi o, thi s i s unfor tunate because i t makes the usage of Date fi el ds i mpossi bl e. The bug mani fests i tsel f i n the fol l owi ng exampl e: addColumn("HIREDATE", java.sql.Date.class, Types.DATE); addColumn("HIREDATE", Types.DATE, Types.DATE); The fi r st cal l fai l s and thr ows a com.ibm.db.DataException (Not supported J ava class is specified in parameter field), but the second cal l works. The same pr obl ems appear wi th ti me stamps: addColumn("HIREDATE", java.sql.Timestamp.class, Types.TIMESTAMP); <== fails addColumn("HIREDATE", Types.TIMESTAMP, Types.TIMESTAMP); <== works Appendix A. Odds and Ends 267 WebSphere Studio When WebSphere Studi o 3 beta 2 i s used to cr eate a ser vl et accessi ng a database, ther e i s a l i ttl e bug when usi ng the opti on Createpagefor when no data is returned (Fi gure 255). Figure255. WebSphereStudioDatabaseWizard I f thi s opti on i s used, the Database Wi zard cr eates a ser vl et cl ass that catches a com.ibm.webtools.runtime.NoDataException. Thi s excepti on i s part of the fi l e webtlsrn.jar, whi ch i s part of the WebSpher e Studi o di stri buti on, but appar entl y i t i s not par t of WebSphere Appl i cati on Ser ver. The r esul t i s that the servl et wi l l not execute at al l when publ i shed to the appl i cati on server because i t cannot fi nd the excepti on cl ass. One wor karound i s si mpl y not to use thi s opti on, but thi s i s not a sol uti on when one woul d l i ke to use the servl ets to update the database. The second possi bi l i ty i s si mpl y to copy the JAR fi l e to the appl i cati on server : from: c:\WebSphere\StudioBeta\lib\AppServerV2\webtlsrn.jar to: c:\WebSphere\AppServer\lib Wi th thi s sol uti on, the generated ser vl et works wel l . 268 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 269 B Special Notices Thi s publ i cati on i s i ntended to hel p Java devel opers devel op enterpr i se appl i cati ons wi th Vi sual Age for Java Enter pri se Versi on 2 and I BM WebSphere, together wi th rel ati onal database systems. The i nfor mati on i n thi s publ i cati on i s not i ntended as the speci fi cati on of any pr ogr ammi ng i nter faces that are provi ded by Vi sual Age for Java Enter pri se and I BM WebSphere. See the PUBLI CATI ONS secti on of the I BM Progr ammi ng Announcement for Vi sual Age for Java Enter pr i se and I BM WebSphere for more i nformati on about what publ i cati ons are consi der ed to be pr oduct documentati on. Refer ences i n thi s publ i cati on to I BM pr oducts, progr ams or servi ces do not i mpl y that I BM i ntends to make these avai l abl e i n al l countr i es i n whi ch I BM oper ates. Any reference to an I BM product, pr ogr am, or servi ce i s not i ntended to state or i mpl y that onl y I BM's pr oduct, progr am, or ser vi ce may be used. Any functi onal l y equi val ent progr am that does not i nfr i nge any of I BM's i ntel l ectual proper ty ri ghts may be used i nstead of the I BM pr oduct, progr am or servi ce. I nformati on i n thi s book was devel oped i n conjuncti on wi th use of the equi pment speci fi ed, and i s l i mi ted i n appl i cati on to those speci fi c hardwar e and software products and l evel s. 270 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server I BM may have patents or pendi ng patent appl i cati ons cover i ng subject matter i n thi s document. The fur ni shi ng of thi s document does not gi ve you any l i cense to these patents. You can send l i cense i nqui r i es, i n wr i ti ng, to the I BM Di r ector of Li censi ng, I BM Cor por ati on, North Castl e Dri ve, Ar monk, NY 10504-1785. Li censees of thi s pr ogram who wi sh to have i nformati on about i t for the pur pose of enabl i ng: (i ) the exchange of i nfor mati on between i ndependentl y cr eated progr ams and other progr ams (i ncl udi ng thi s one) and (i i ) the mutual use of the i nfor mati on whi ch has been exchanged, shoul d contact I BM Corporati on, Dept. 600A, Mai l Dr op 1329, Somers, NY 10589 USA. Such i nformati on may be avai l abl e, subject to appr opr i ate terms and condi ti ons, i ncl udi ng i n some cases, payment of a fee. The i nformati on contai ned i n thi s document has not been submi tted to any for mal I BM test and i s di str i buted AS I S. The i nformati on about non-I BM ("vendor ") products i n thi s manual has been suppl i ed by the vendor and I BM assumes no r esponsi bi l i ty for i ts accuracy or compl eteness. The use of thi s i nfor mati on or the i mpl ementati on of any of these techni ques i s a customer responsi bi l i ty and depends on the customer 's abi l i ty to eval uate and i ntegrate them i nto the customer's oper ati onal envi r onment. Whi l e each i tem may have been r evi ewed by I BM for accuracy i n a speci fi c si tuati on, there i s no guarantee that the same or si mi l ar r esul ts wi l l be obtai ned el sewher e. Customer s attempti ng to adapt these techni ques to thei r own envi r onments do so at thei r own ri sk. Any poi nters i n thi s publ i cati on to exter nal Web si tes ar e provi ded for conveni ence onl y and do not i n any manner serve as an endor sement of these Web si tes. Any perfor mance data contai ned i n thi s document was deter mi ned i n a control l ed envi r onment, and ther efor e, the r esul ts that may be obtai ned i n other operati ng envi r onments may var y si gni fi cantl y. Users of thi s document shoul d veri fy the appl i cabl e data for thei r speci fi c envi r onment. Thi s document contai ns exampl es of data and reports used i n dai l y busi ness oper ati ons. To i l l ustr ate them as compl etel y as possi bl e, the exampl es contai n the names of i ndi vi dual s, compani es, br ands, and pr oducts. Al l of these names ar e fi cti ti ous and any si mi l ari ty to the names and addresses used by an actual busi ness enterpr i se i s enti r el y coi nci dental . Refer ence to PTF number s that have not been r el eased through the nor mal di str i buti on process does not i mpl y gener al avai l abi l i ty. The pur pose of i ncl udi ng these reference number s i s to al er t I BM customer s to speci fi c i nfor mati on rel ati ve to the i mpl ementati on of the PTF when i t becomes Appendix B. Special Notices 271 avai l abl e to each customer accor di ng to the normal I BM PTF di stri buti on process. The fol l owi ng ter ms are trademar ks of the I nter nati onal Busi ness Machi nes Corporati on i n the Uni ted States and/or other countr i es: The fol l owi ng ter ms are trademar ks of other compani es: C-bus i s a tr ademark of Corol l ar y, I nc. i n the Uni ted States and/or other countr i es. Java and al l Java-based tr ademarks and l ogos are tr ademarks or regi stered trademarks of Sun Mi cr osystems, I nc. i n the Uni ted States and/or other countr i es. Mi crosoft, Wi ndows, Wi ndows NT, and the Wi ndows l ogo ar e trademar ks of Mi crosoft Corporati on i n the Uni ted States and/or other countr i es. PC Di rect i s a tr ademark of Zi ff Communi cati ons Company i n the Uni ted States and/or other countri es and i s used by I BM Cor por ati on under l i cense. Acti onMedi a, LANDesk, MMX, Penti um and Pr oShare are trademar ks of I ntel Corporati on i n the Uni ted States and/or other countr i es. UNI X i s a r egi ster ed tr ademark i n the Uni ted States and/or other countr i es l i censed excl usi vel y through X/Open Company Li mi ted. SET and the SET Logo are trademar ks owned by SET Secur e El ectroni c Transacti ons LLC. Other company, product, and ser vi ce names may be tr ademarks or servi ce marks of others. I BM AS/400 DB2 CI CS OS/2 OS/390 OS/400 S/390 TeamConnecti on Thi nkPad Vi sual Age WebSphere 272 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 273 C Related Publications The publ i cati ons l i sted i n thi s secti on ar e consi der ed parti cul arl y sui tabl e for a mor e detai l ed di scussi on of the topi cs covered i n thi s r edbook. 274 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server International Technical Support Organization Publications For i nfor mati on on order i ng these I TSO publ i cati ons see How to Get I TSO Redbooks on page 277. Developing an e-Business Application for theWebSphereApplication Server, SG24-5423 VisualAgefor J ava EnterpriseVersion 2: PersistenceBuilder with GUI s, Servlets, and J ava Server Pages, SG24-5426 WebSphereApplication Servers - Standard and Advanced, SG24-5460 EnterpriseJ avaBeans Development Using VisualAgefor J ava, SG24-5429 J ava Application Development for CI CS: BaseServices and CORBA Client Support, SG24-5275 UsingVisualAgeSmalltalk ObjectExtender, SG24-5258 VisualAgefor J ava EnterpriseVersion 2: Data Access Beans - Servlets - CI CS Connector, SG24-5265 Programmingwith VisualAgefor J ava Version 2, SG24-5264, publ i shed by Prenti ce Hal l , I SBN 0-13-021298-9, 1999 (I BM form number SR23-9016) VisualAgefor J ava EnterpriseVersion 2 TeamSupport, SG24-5245 Using VisualAgefor J ava EnterpriseVersion 2 toDevelop CORBA and EJ B Applications, SG24-5276 VisualAgeJ ava-RMI -Smalltalk, TheATM SamplefromA toZ, SG24-5418 UsingVisualAgeUML Designer, SG24-4997 Application Development with VisualAgefor J ava Enterprise, SG24-5081 Creating J ava Applications with NetRexx, SG24-2216 Unlimited EnterpriseAccess with J ava and VisualAgeGenerator, SG24-5246 FromClient/ Server to Network Computing, A Migration to J ava, SG24-2247 ConnectingtheEnterprisetotheI nternet with MQSeries and VisualAgefor J ava, SG24-2144 Appendix C. Related Publications 275 Redbooks on CD-ROMs Redbooks ar e al so avai l abl e on the fol l owi ng CD-ROMs. Cl i ck the CD-ROMs button at http://www.redbooks.ibm.com/ for i nfor mati on about al l the CD-ROMs offer ed, updates and formats. Other Publications These publ i cati ons ar e al so r el evant as further i nformati on sour ces: Devel opi ng J avaBeans with VisualAgefor J ava Version 2, SC34-4735 Design Patterns: El ements of Reusabl eObject-Ori ented Software, Er i ch Gamma, Ri chard Hel m, Ral ph Johnson, and John Vl i ssi des, publ i shed by Addi son-Wesl ey Pr ofessi onal Computi ng Ser i es, I SBN 0-201-63361, 1995 (I BM for m number SR28-5629) CD-ROM Title Collection Kit Number System/390 Redbooks Col l ecti on SK2T-2177 Networ ki ng and Systems Management Redbooks Col l ecti on SK2T-6022 Tr ansacti on Processi ng and Data Management Redbooks Col l ecti on SK2T-8038 Lotus Redbooks Col l ecti on SK2T-8039 Ti vol i Redbooks Col l ecti on SK2T-8044 AS/400 Redbooks Col l ecti on SK2T-2849 Netfi ni ty Har dwar e and Softwar e Redbooks Col l ecti on SK2T-8046 RS/6000 Redbooks Col l ecti on (BkMgr) SK2T-8040 RS/6000 Redbooks Col l ecti on (PDF For mat) SK2T-8043 Appl i cati on Devel opment Redbooks Col l ecti on SK2T-8037 I BM Enter pri se Stor age and Systems Management Sol uti ons SK3T-3694 276 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 277 How to Get ITSO Redbooks Thi s secti on expl ai ns how both customer s and I BM empl oyees can fi nd out about I TSO redbooks, redpi eces, and CD-ROMs. A form for or der i ng books and CD-ROMs by fax or e-mai l i s al so pr ovi ded. Redbooks Web Site http://www.redbooks.ibm.com/ Search for, vi ew, downl oad or or der har dcopy/CD-ROM redbooks from the redbooks web si te. Al so r ead r edpi eces and downl oad addi ti onal materi al s (code sampl es or di skette/CD-ROM i mages) fr om thi s redbooks si te. Redpi eces are r edbooks i n pr ogress; not al l redbooks become redpi eces and someti mes just a few chapters wi l l be publ i shed thi s way. The i ntent i s to get the i nformati on out much qui cker than the formal publ i shi ng pr ocess al l ows. E-mail Orders Send orders by e-mai l i ncl udi ng i nformati on from the redbooks fax order form to: Telephone Orders Fax Orders Thi s i nformati on was cur rent at the ti me of publ i cati on, but i s conti nual l y subject to change. The l atest i nformati on may be found at the r edbooks Web si te. I n Uni ted States Outsi de Nor th Amer i ca e-mail address usi b6fpl @i bmmai l .com Contact i nformati on i s i n the How to Or der secti on at thi s si te: http://www.elink.ibmlink.ibm.com/pbl/pbl/ Uni ted States (tol l free) Canada (tol l fr ee) Outsi de North Amer i ca 1-800-879-2755 1-800-I BM-4YOU Countr y coor di nator phone number i s i n the How to Or der secti on at thi s si te: http://www.elink.ibmlink.ibm.com/pbl/pbl/ Uni ted States (tol l fr ee) Canada Outsi de Nor th Amer i ca 1-800-445-9269 1-403-267-4455 Fax phone number i s i n the How to Or der secti on at thi s si te: http://www.elink.ibmlink.ibm.com/pbl/pbl/ I BM empl oyees may regi ster for i nformati on on workshops, resi denci es, and redbooks by accessi ng the I BM I ntr anet Web si te at http://w3.itso.ibm.com/ and cl i cki ng the I TSO Mai l i ng Li st button. Look i n the Materi al s r eposi tory for wor kshops, pr esentati ons, paper s, and Web pages devel oped and wri tten by the I TSO techni cal pr ofessi onal s; cl i ck the Addi ti onal Materi al s button. Empl oyees may access MyNews at http://w3.ibm.com/ for redbook. r esi dency, and wor kshop announcements. IBM Intranet for Employees 278 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server IBM Redbook Fax Order Form Pleasesend methefollowing: Weaccept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card not availablein all countries. Signaturemandatory for credit card payment. Title Order Number Quantity Fi r st name Last name Company Addr ess Ci ty Postal code Tel ephone number Tel efax number VAT number I nvoi ce to customer number Countr y Cr edi t car d number Credi t car d expi rati on date Si gnatur e Car d i ssued to Copyright IBM Corp. 1999 279 List of Abbreviations API appl i cati on progr ammi ng i nter face ASP Acti ve Ser ver Pages ATM automated tel l er machi ne AWT Abstract Wi ndowi ng Tool ki t CGI Common Gateway I nter face CORBA Common Object Request Br oker Archi tecture DBMS database management system DLL dynami c l i nk l i brar y GUI gr aphi cal user i nter face HTML Hyper text Mar kup Language HTTP Hyper text Tr ansfer Pr otocol I BM I nter nati onal Busi ness Machi nes Corpor ati on I DE i ntegrated devel opment envi r onment I TSO I nter nati onal Techni cal Suppor t Or gani zati on J AR Java ar chi ve J DBC Java Database Connecti vi ty J DK Java Devel oper s Ki t J FC Java Foundati on Cl asses J SDK Java Servl et Devel opment Ki t J SP Java Server Pages J VM Java Vi rtual Machi ne ODBC Open Database Connecti vi ty PI N per sonal i denti fi cati on number RDBMS rel ati onal database management system RMI Remote Method I nvocati on SQL structur ed quer y l anguage TCP/I P Transmi ssi on Contr ol Protocol /I nter net Protocol UOW uni t of work URL uni form r esour ce l ocator WWW Wor l d Wi de Web 280 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server Copyright IBM Corp. 1999 281 Index A access contr ol l i st 238 al i as 4 Apache 4, 5 Appl i cati on Server see WebSpher e assembl y stages 196 B bean managed per si stence 132, 164 C cl ass path 129 Java 60 Per si stence Bui l der 130 Vi sual Age for Java 48 WebSphere 49, 129 WebSphere Studi o 181 confi gur ati on secur i ty 241 Vi sual Age for Java 10 WebSphere 6 WebSphere Studi o 181 publ i shi ng 194 connecti on data access beans 89 JDBC 83, 112 connecti on manager 65, 84 JDBC 69 sampl e 70 data access beans 98 DB2 77 Or acl e 79 SQL Ser ver 79 servl et i nter acti on 66 connecti on pool 67, 68, 84 contai ner managed persi stence 132, 133 D data access beans 81 EJB per si stence 167 output tai l or i ng 96 sampl e connecti on manager 98 DB2 86 Or acl e 95 SQL Ser ver 95 servl et sampl e 86 SQL types 266 Database Wi zard 188, 200 datastor e acti vati on 126 DB2 appl i cati on dri ver 44 Cl i ent Appl i cati on Enabl er 44 Command Wi ndow 24 Contr ol Center 22 cr eate database 23 data l oad 26 fi xpack 22, 247 i nstal l ati on 22 JDBC 44, 82 appl et ser ver 45 dr i vers 26 network dri ver 45, 56 sampl e connecti on manager 77 data access beans 86 EJB 170 JDBC 56 Persi stence Bui l der 112, 127 SQLJ 251 WebSphere Studi o 183 Softwar e Devel oper s Ki t 250 SQL types 264 SQLJ 22, 249 tabl e creati on 24 DBNavi gator bean 82 debuggi ng Vi sual Age for Java 210 di r ector y servi ce 238, 245 document r oot 4 E EJB contai ner 132, 133, 166 Devel opment Envi r onment Vi sual Age for Java 134 fi el ds 138 282 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server gener ate code 143 gr oup 134 mappi ng 142 methods 139 pr i mary key 137 sampl e DB2 133 servl et 174 server 132, 133, 143, 144 test cl i ent 145 enterpri se bean appl i cati on sampl e 160 depl oyment 149, 177, 266 servl et sampl e 153 test 143 test cl i ent 145 Enter pr i se Java Ser ver 132 Enter pr i se JavaBeans archi tectur e 131 see al so enter pr i se beans Enter pr i se Update 10 enti ty bean 132 H home i nterface 132, 146 HTML vi sual composi ti on 122 HTTP Server 3, 152, 195 i nstal l ati on 4 I i mpor t schema 112 i nstal l ati on DB2 UDB 22 HTTP Server 4 Or acl e 27 SQL Ser ver 33 Vi sual Age for Java 10 WebSphere 5 WebSphere Studi o 181 I nter net Expl orer 3 i terator 254 I TSO pr oject 17 user I D 23 i tso.wasdb.accessbean package 86 i tso.wasdb.connaccess package 98 i tso.wasdb.connmgr package 70 i tso.wasdb.ejb package 134 i tso.wasdb.ejb.cl i ent package 160 i tso.wasdb.jdbc package 53 i tso.wasdb.per si st package 118 i tso.wasdb.per si st.gui package 121 i tso.wasdb.per si st.metadata package 121 i tso.wasdb.per si st.Ser vi ces package 120 i tso.wasdb.studi o package 191 J Java Database Connecti vi ty see JDBC Java Foundati on Cl asses see Swi ng JavaServer Pages see JSP JDBC appl et ser ver 56 connecti on 83, 112 manager 69 DB2 26, 44 dr i vers 43 ODBC br i dge 38, 47, 82 Or acl e 27, 32, 46 pr ogrammi ng exampl es 53 resul t set 85 sampl e DB2 56 Or acl e 57 run 60 SQL Ser ver 58 test 60 servl et 61 si mpl e appl i cati on 53 SQL cl asses 82 SQL Ser ver 38, 47 SQLJ 248 statement types 85 URL 150 Vi sual Age for Java 10, 48 WebSphere 7, 49 JSP 12, 180, 187, 193 servl et i nvocati on 202 JSP Page Compi l e Gener ated Code 12 JTabl e 82 283 L LDAP 238, 240 Lotus Domi no Go Webser ver 5 M Map Br owser 111, 116, 142 Model Br owser 111, 115 N NetObjects BeanBui l der 180 Fusi on 180 Scr i ptBui l der 180 Netscape Di rector y Ser ver 238 Enter pr i se Ser ver 5 Navi gator 3 O ODBC 82 data source 38, 47, 58 Or acl e cr eate tabl es 29 data l oad 31 i nstal l ati on 27 JDBC 27, 32, 46 OCI dr i ver 46 Per si stence Bui l der 111 sampl e connecti on manager 79 data access beans 95 EJB 170 JDBC 57 Per si stence Bui l der 127 WebSphere Studi o 184 SQL types 264 thi n cl i ent dri ver 46 user I D 27 P Page Desi gner 202 per si stence 110 Per si stence Bui l der 109 EJB mappi ng 140 pal ette 123 resul t tabl e 125 sampl e 112 DB2 127 Or acl e 127 ser vl et 121 SQL Ser ver 127 tool s 110 pr i mary key 137 pr oject vi ew 192, 212 Q Qui ck Start 10, 82 R real m 238, 239 rel ati onal database pr oducts 21 remote i nterface 133 reposi tory 17 resour ce 240 resul t set JDBC 85 SQLJ 256 Rol l up 2 10 S sampl e code 15 database 21 Schema Br owser 111, 112, 140 schema i mpor t 112 Secure Socket Layer 4 secur i ty 237 Sel ect bean 81, 82, 88 sel ect statement data access beans 91 SQLJ 256 seri al i zati on 110 SQLJ 249 SERunner 12, 97, 106, 158 cl ass path 12 servi ce cl asses 119 servl et confi gur ati on fi l e 208, 210 confi gur ati onl fi l e 11 data access beans 86 depl oyment 107, 128 di r ector y 11 EJB sampl e 153, 174 284 IBM WebSphere and VisualAge for Java Database Integration with DB2, Oracle, and SQL Server JDBC sampl e 61 l auncher 63, 106 l ocati on 7 Per si stence Bui l der sampl e 121 run Vi sual Age for Java 12, 63, 97 WebSphere 63 secur i ty 243 SQLJ sampl e 251 test 197 URL 7 vi sual composi ti on 86 WebSphere Studi o sampl e 188 Ser vl et Bui l der 86, 122 sessi on bean 132 Smar tGui de EJB 136 Per si stence Bui l der code generati on 118 SQL Assi st 81, 91 SQL types 171, 264 SQL Assi st Smar tGui de 81, 91 SQL Ser ver cr eate database 33 cr eate tabl es 34 data l oad 35 i nstal l ati on 33 JDBC 38, 47 Per si stence Bui l der 111 sampl e connecti on manager 79 data access beans 95 EJB 170 JDBC 58 Per si stence Bui l der 127 WebSphere Studi o 184 SQL types 264 user I D 34 SQL Wi zar d 183, 198 SQLJ 22, 247 depl oyment 258 i terator 254 sel ect 256 tr ansl ator 249, 250 Swi ng 82 T test cl i ent 145, 152, 174 U UDB see DB2 V Vi sual Age for Java 9 cl ass path 48 enterpri se bean test 143 export 159 i nstal l ati on 10 JDBC 10, 48 test 60 per si stence bui l der 109 Professi onal Edi ti on 180 Ser vl et Bui l der 86 servl et debuggi ng 210 setup for EJB 134 SQLJ 248 W WebSphere 3, 5 admi ni strati on 6, 7, 67, 129 cl ass path 129 EJB depl oyment 149, 177 i nstal l ati on 5 Java engi ne 129 JDBC 7, 49 servl et depl oyment 107, 128 ser vi ce 8, 152 SQLJ depl oyment 258 start/stop 8 Studi o 179 Test Envi ronment 10, 63, 158 cl ass path 13 WebSphere Studi o Page Desi gner 202 publ i sh 194 sampl e DB2 183 Or acl e 184 ser vl et 188 SQL Ser ver 184 X XML servl et confi gurati on fi l e 11, 193, 210 Copyright IBM Corp. 1999 285 ITSO Redbook Evaluation I BM WebSphere and Vi sual Age for Java Database I ntegr ati on wi th DB2, Oracl e, and SQL Ser ver SG24-5471-00 Your feedback i s ver y i mpor tant to hel p us mai ntai n the qual i ty of I TSO r edbooks. Please complete this questionnaire and return it using one of the following methods: Use the onl i ne eval uati on for m found at http://www.redbooks.ibm.com/ Fax thi s form to: USA I nter nati onal Access Code + 1 914 432 8264 Send your comments i n an I nter net note to redbook@us.ibm.com Whi ch of the fol l owi ng best descr i bes you? _ Customer _ Business Partner _ Solution Developer _ I BM employee _ None of the above Please rate your overall satisfaction wi th thi s book usi ng the scal e: (1 =very good, 2 =good, 3 =average, 4=poor, 5 =very poor) Overal l Sati sfacti on __________ Please answer the following questions: Was thi s r edbook publ i shed i n ti me for your needs? Yes___ No___ I f no, pl ease expl ai n: What other r edbooks woul d you l i ke to see publ i shed? Comments/Suggestions: (THANK YOU FOR YOUR FEEDBACK!) Printed in the U.S.A. SG24-5471-00 I B M W e b S p h e r e a n d V i s u a l A g e f o r J a v a D a t a b a s e I n t e g r a t i o n w i t h D B 2 , O r a c l e , a n d S Q L S e r v e r S G 2 4 - 5 4 7 1 - 0 0