lab book: java projections - hs-weingarten.de · lab book: java projections iii ... the appendix...

74
Lab Book: Java Projections Version InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Upload: others

Post on 29-May-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Lab Book: JavaProjections

Version

InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Lab Book: Java ProjectionsVersion

Copyright © 2005 InterSystems Corporation.All rights reserved.

This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information fromthe following sources: Sun Microsystems, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium atwww.w3c.org. The primary document development tools were special-purpose XML-processing applications builtby InterSystems using Caché and Java.

The Caché product and its logos are trademarks of InterSystems Corporation.

The Ensemble product and its logos are trademarks of InterSystems Corporation.

The InterSystems name and logo are trademarks of InterSystems Corporation.

This document contains trade secret and confidential information which is the property of InterSystems Corporation,One Memorial Drive, Cambridge, MA 02142, or its affiliates, and is furnished for the sole purpose of the operationand maintenance of the products of InterSystems Corporation. No part of this publication is to be used for any otherpurpose, and this publication is not to be reproduced, copied, disclosed, transmitted, stored in a retrieval system ortranslated into any human or computer language, in any form, by any means, in whole or in part, without the expressprior written consent of InterSystems Corporation.

The copying, use and disposition of this document and the software programs described herein is prohibited exceptto the limited extent set forth in the standard software license agreement(s) of InterSystems Corporation coveringsuch programs and related documentation. InterSystems Corporation makes no representations and warrantiesconcerning such software programs other than those set forth in such standard software license agreement(s). Inaddition, the liability of InterSystems Corporation for any losses or damages relating to or arising out of the use ofsuch software programs is limited in the manner set forth in such standard software license agreement(s).

THE FOREGOING IS A GENERAL SUMMARY OF THE RESTRICTIONS AND LIMITATIONS IMPOSED BYINTERSYSTEMS CORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTERSOFTWARE. FOR COMPLETE INFORMATION REFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARELICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION, COPIES OF WHICH WILL BE MADE AVAILABLEUPON REQUEST.

InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves theright, in its sole discretion and without notice, to make substitutions and modifications in the products and practicesdescribed in this document.

Caché, InterSystems Caché, Caché SQL, Caché ObjectScript, Caché Object, Ensemble, InterSystems Ensemble,Ensemble Object, and Ensemble Production are trademarks of InterSystems Corporation. All other brand or productnames used herein are trademarks or registered trademarks of their respective companies or organizations.

For Support questions about any InterSystems products, contact:

InterSystems Worldwide Customer Support+1 617 621-0700Tel:+1 617 374-9391Fax:[email protected]:

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Table of Contents

Preface ................................................................................................................................. 1Contents of this Book ..................................................................................................... 1How To Use this Book .................................................................................................... 2

1 The Basics ......................................................................................................................... 31.1 Introduction .............................................................................................................. 31.2 Overview: Caché Java Binding Basics .................................................................... 31.3 Java Binding Quick Start ......................................................................................... 41.4 Java Binding Components and Resources ............................................................... 61.5 Java Projections ........................................................................................................ 71.6 Runtime Architecture ............................................................................................... 71.7 Full and Light Binding ............................................................................................. 81.8 Quiz One .................................................................................................................. 81.9 Creating Projections ................................................................................................. 91.10 Projection Details: Identifiers and Data Types ..................................................... 101.11 Projection Details: Collections ............................................................................ 111.12 Projection Details: /NEWCOLLECTIONS Flag ................................................. 121.13 Projection Details: Queries .................................................................................. 131.14 Projection Details: Persistent Classes .................................................................. 141.15 Quiz Two .............................................................................................................. 151.16 Establishing a Connection: Full and Light ........................................................... 161.17 Opening an Existing Object ................................................................................. 171.18 Creating a New Object ......................................................................................... 181.19 Using Collections ................................................................................................ 191.20 Using a Relationship ............................................................................................ 201.21 Quiz Three ............................................................................................................ 201.22 Overview: Caché JDBC ...................................................................................... 221.23 Caché JDBC Quick Start ..................................................................................... 221.24 JDBC Components and Resources ...................................................................... 231.25 Connection Options ............................................................................................. 241.26 Connecting Using DriverManager ....................................................................... 241.27 Connecting Using CacheDatabase ....................................................................... 251.28 Executing a SELECT ........................................................................................... 261.29 Executing an INSERT .......................................................................................... 27

Lab Book: Java Projections                                                                                                                   iii

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.30 Quiz Four ............................................................................................................. 271.31 Caché Custom JSP Tag Overview ........................................................................ 281.32 Caché Custom Tag Resources .............................................................................. 291.33 Installing and Executing the Samples .................................................................. 301.34 Some Caché Custom Tags and their Attributes .................................................... 311.35 The <list> Tag ...................................................................................................... 311.36 Using Custom Tags .............................................................................................. 321.37 Quiz Five .............................................................................................................. 331.38 Design Considerations: Java Binding or JDBC? ................................................. 34

2 Lab Project ..................................................................................................................... 352.1 Project Overview .................................................................................................... 352.2 Project One: Currency Order through an ATM ..................................................... 352.3 Project Two: Credit Card and Customer Account Payments ................................. 36

3 Advanced Topics ............................................................................................................ 393.1 Overview ................................................................................................................ 393.2 Overview: Caché Java Binding Advanced Features .............................................. 393.3 Using a Class Query ............................................................................................... 403.4 Using a Dynamic Query ......................................................................................... 403.5 Using OpenByQuery and a Simple Condition ....................................................... 413.6 Using OpenByQuery and a Complex Query .......................................................... 423.7 Calling By Reference and Output Arguments ........................................................ 433.8 Using Dynamic Binding ........................................................................................ 443.9 Using Batch Inserts ................................................................................................ 453.10 Using Transactions ............................................................................................... 463.11 Overview: JDBC Advanced Features ................................................................... 473.12 Using a Connection Pool ..................................................................................... 483.13 Using Implicit Joins ............................................................................................. 493.14 JDBC Transaction API ......................................................................................... 503.15 Using JDBC Transactions .................................................................................... 513.16 Retrieving Generated Keys .................................................................................. 513.17 Executing a Stored Procedure .............................................................................. 523.18 Executing a Stored Procedure: Multiple Result Sets ........................................... 533.19 Scrolling in a Result Set ....................................................................................... 543.20 Updating a Result Set ........................................................................................... 56

Appendix A: Answers to Quiz Questions ........................................................................ 57

iv                                                                                                                   Lab Book: Java Projections

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Appendix B: Solutions for Project One .......................................................................... 59

Appendix C: Starter Files for Project One — Swing Version ...................................... 61

Appendix D: Starter Files for Project One — Web Version ......................................... 65

Lab Book: Java Projections                                                                                                                    v

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Preface

Caché 5.2 provides several different options for connecting Java client applications to Caché.These options include:

• Caché JDBC driver (relational interface). Standard type 4 JDBC driver that provides arelational access to Caché data. The Caché 5.2 JDBC driver supports all required JDBC3.0 features.

• Caché Java Binding Mechanism. Built on top of the JDBC driver, this mechanism providesa pure object interface to Caché. Using this mechanism, Caché generates pure Java classesfrom your Caché classes. These Java “projection” classes serve as proxies for theirCaché counterparts. This mechanism requires no object-relational mapping or additionalmiddleware.

• Caché Custom JSP Tag Library. A set of custom JSP tags that provide simple and efficientaccess to Caché data, including Caché objects, from within Java Web applications.

• Web Services. Caché provides resources for rapidly building Web Services that can beaccessed by Java applications using standard Java Web Services libraries.

• JALAPEÑO. Java Language Persistence with No Mapping. This mechanism providesanother pure object interface to Caché. The mechanism generates Caché classes and adatabase schema from your Java POJO (Plain Ordinary Java Object) classes. It alsoprovides APIs for managing the persistence of POJOs to Caché.

Contents of this BookThis lab book contains information and examples to help you use the JDBC relational interface,the Java Binding mechanism, as well as the custom JSP tags. The book also provides labprojects that involve creating various Java clients for the Foreign Cash Exchange Cachéapplication (built during the Caché Foundation I and II courses). The book is divided intothree sections:

1. The Basics — Provides information and examples to help you use the basic features ofthe Caché Java Binding, JDBC, and the custom JSP tags. After reading this section, youwill have sufficient information to complete the lab projects.

2. Lab Projects — Presents several Lab Projects as sets of use case descriptions. These usecases describe Java user interfaces for the Caché Foreign Cash Exchange application

Lab Book: Java Projections                                                                                                                   1

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

that you built in the Foundation courses. Note that solutions and partial solutions forseveral of the projects are provided separately.

3. Advanced Features — Provides information and examples to help you use features ofthe Caché Java Binding, JDBC, and JSP tags not described in The Basics. Before com-pleting the lab projects, you should glance at this section to find features that you mightbe interested in using. None of the features described in this section are necessary forcompleting any of the lab projects.

How To Use this BookYour goal should be to complete at least one of the Lab Projects. You are also stronglyencouraged to try using the Caché Java Binding to connect to your Java application to Caché.Here is one way to proceed:

1. Skip ahead to the Lab Projects section to familiarize yourself with the requirements forat least one of the lab projects.

2. Read through Part 1: The Basics.

3. Develop a preliminary design for your lab project solution. Refer to the Design Consid-erations sections of Part I.

4. Skim through Part III: Advanced Features and select any that you would like to use inyour lab project solution.

5. Start building your lab project solution. Use the lab book as a reference manual.

Note: Caché 5.2 supports both Java 1.4 and 1.5. JALAPEÑO requires Java 1.5.

This lab book does not cover connecting Java applications to Caché Web Services.The Foundation I and II courses covered creating Caché Web Services. You canbuild a Java Web service client for a Caché Web service using standard Java WebService libraries and techniques. For information on building Java Web servicec l i e n t s s e e S u n M i c r o s y s t e m ' s J 2 E E Tu t o r i a l a thttp://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html.

2                                                                                                                   Lab Book: Java Projections

Preface

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1The Basics

1.1 Introduction

This section presents information and examples to help you use the basic features of theCaché Java Binding, JDBC, and custom JSP tags. After completing this section, you willhave sufficient information to complete the projects described in the Lab Projects sections.Along the way, the section provides quizzes to help you reinforce your understanding of thematerial. The Appendix contains the answers to the quiz questions. The section is dividedinto four parts:

1. Java Bindings — Presents the basics of the Caché Java Binding Mechanism.

2. Caché JDBC — Presents the basics of the Caché JDBC relational interface.

3. Caché Custom JSP Tags — Presents the basics of the Caché Custom JSP Tags.

4. Design Considerations — Presents some of the key design considerations for using aJava application with Caché.

1.2 Overview: Caché Java Binding Basics

The Caché Java Binding provides an object interface that allows Java applications to directlyaccess Caché objects, both persistent and transient, on the Caché server. The Java Bindingrequires no additional middleware or object-relational mappings. The Caché Java Bindingprovides complete support for object database persistence including concurrency and trans-

Lab Book: Java Projections                                                                                                                   3

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

action control. In addition, the mechanism provides a sophisticated caching scheme to helpminimize network traffic between the Java application environment and the Caché server.The Caché Java Binding supports all of the following:

1. Creating and saving Caché objects.

2. Opening, modifying, and saving existing Caché objects.

3. Manipulating Caché collections and relationships.

4. Executing stored procedures and dynamic queries.

5. Performing batch inserts.

6. Using transactions.

7. Binding dynamically to Caché objects.

This section begins with a Quick Start guide for connecting to Caché and updating an existingCaché object. The section then presents information on the components and architecture ofthe Caché Java Binding and finally covers topic 1—3. The Advanced Features section coverstopics 4–7.

1.3 Java Binding Quick Start

Here are the basic steps for using the Caché Java Binding Mechanism to modify a Cachéobject:

1. Create and compile a Java Projection for the class:

Create the projection using Caché Terminal:

SAMPLES>Do $System.OBJ.ExportJava("Sample.Person","C:\MyJavaProjections")

Compile the Java projection using your Java compiler. Note that CacheDB.jar must beon your class path:

C:\MyProjections\Sample>javac -classpath C:\CacheSys\Dev\Java\Lib\JDK14\CacheDB.jar *.java

2. Add code to your Java application that opens and uses instances of Sample.Person:

Import the required packages:

4                                                                                                                   Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

import com.intersys.objects.*;

Create a connection to Caché:

Database db = CacheDatabase.GetDatabase("jdbc:Cache://localhost:1972/<Namespace>", <User>, <Pwd>);

Open an existing object:

if (id == null) id = new Id( 1 );Sample.Person person = (Sample.Person)Sample.Person._open(db,id);

Retrieve property values using get methods:

System.out.println("Name: " + person.getName());System.out.println("DOB: " + person.getDOB());

Set property values using set methods:

person.setName(newName);person.setDOB(newDOB);

Save the changes to the object:

person.save();

Close the object. Note that the proper way to close an object is to use the CloseObjectmethod of CacheDatabase. Each object supports a _close method, however this methodis deprecated and should not be used.

db.closeObject(person.getOref());

Close the database connection.

db.close();

Note: All of the above methods throw exceptions of type CacheException.

Lab Book: Java Projections                                                                                                                   5

Java Binding Quick Start

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.4 Java Binding Components and Resources

The Caché Java Binding mechanism contains the following components:

• The Caché Object Server — A high-performance server process that manages communi-cation between Java clients and a Caché database server. It communicates using TCP/IPand can execute on any platform supported by Caché. All Caché language bindings: Java,C++, Perl, Python, JDBC, and ODBC, use the Caché Object Server.

• CacheDB.jar — Two different versions. One is located in <cachesys>\dev\java\lib\JDK14.Use this if you are using Java 1.4.x. Another version is located in<cachesys>\dev\java\lib\JDK15. Use this version if you are using Java 1.5.x. Note thatwhen using JALAPEÑO you must use Java 1.5.x. The archives contain several packagesof Java classes that provide the connection and caching mechanisms for communicationwith the Caché server, JDBC connectivity, and reflection support. CacheDB.jar must beon the class path when compiling or using Java projection classes.

• Caché Java Class Generator — An extension to the Caché Compiler. If you add a Projection

definition to a class then the compiler generates the Java Projection whenever the classis compiled. You can also generate Java Projections using Caché Terminal withoutdefining a Projection.

In addition to these components, a standard Caché installation contains a number of otherresources to help you use the Caché Java Binding:

• “JavaDoc” style class documentation for the packages in CacheDB.jar. This documentationis in <cachesys>\Dev\java\doc.

• A set of sample Java programs that demonstrate the use of the Java Binding to connectto Caché, open existing objects, create new objects, save object changes to Caché andexecute queries against Caché. These sample programs are in <cachesys>\dev\java\samples.

• Caché documentation: See Using Java with Caché within the Caché Language Bindingssection of the Caché documentation.

• Tutorials: See Caché with Java and J2EE QuickStart Tutorial inside the Caché Tutorialssection of the Caché documentation.

Note: In a standard Windows installation, <cachesys> is C:\CacheSys.

In a standard Unix or Linux installation, <cachesys> is /usr/cachesys.

6                                                                                                                   Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.5 Java Projections

From the perspective of a Java application, Java Projections form the heart of the JavaBinding mechanism. A Java projection of a Caché class is a pure Java class that serves as aproxy for a Caché class within the Java application. A Java projection of a Caché class providesa communication link between the Java application and the Caché class. The Java applicationuses the projection like any other Java class: creating instances, calling methods, getting andsetting property values and so on. The projection, in turn, invokes the corresponding methodson the Caché classes and object on the Caché server.

1.6 Runtime Architecture

At runtime, the Java Binding works in the following way:

1. A Java object sends a message to a Java Projection object.

2. The Java Projection forwards the message to the appropriate classes in CacheDB.jar.

3. CacheDB.jar forwards the message to the Caché Object Server using TCP/IP.

4. The Caché Object Server forwards the message to the appropriate Caché object.

5. The Caché Object Server sends the return message to the Java object through CacheDB.jar

and the Java Projection object.

Lab Book: Java Projections                                                                                                                   7

Java Projections

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Note: The Java Binding caches the values of object properties on the client-side. So, whenthe Java application invokes a “Get” method for a property, there is no call to theserver. The property value is returned immediately by the projection object.

1.7 Full and Light Binding

The Caché Java Binding supports two different variations: Light Binding and Full Binding.The following table describes their differences and a few considerations for choosing betweenthem.

Full and Light Binding Comparison

CapabilitiesBinding Type

Provides access to Caché object properties (through get and set methods)and class methods, but not Caché instance methods in general. It alsoprovides access to Caché stored procedures.

Light Binding

Provides access to Caché object properties, class methods, and instancemethods as well as Caché stored procedures.

Full Binding

1.8 Quiz One

Question 1: Which one of the following must be on your Java application's class path whenusing the Caché Java Binding?

1. <cachesys>\dev\java\lib\JDK14

2. CacheDB.jar

3. CacheBinding.jar

4. CacheObject.dll

5. The Caché Object Server

Question 2: Which one of the following best describes the differences between the Full andLight Java Binding?

8                                                                                                                   Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1. The Light Binding requires that an application use fewer Java projections of Caché classesthan the Full Binding.

2. The Light Binding supports only a relational interface to the database whereas the FullBinding supports both a relational and an object interface.

3. The Light Binding uses only projections of transient classes whereas the Full Bindinguses projections of both transient and persistent classes.

4. The Light Binding provides greater effiency, but less functionality than the Full Binding.

5. The Light Binding includes the same functionality, but is less scalable than the FullBinding.

Question 3: Which one of the following best defines “Java Projection” ?

1. A Java class installed by Caché that wraps the Caché JDBC driver.

2. A Java class generated by an object-relational mapping tool that maps Java objects toCaché data.

3. A Java class automatically generated by Caché that contains SQL queries for accessingCaché data.

4. A Java class that instantiates a connection to Caché.

5. A Java class that serves as a proxy for a Caché class within a Java application.

1.9 Creating Projections

There are two ways to create a Java Projection for a Caché class:

1. Execute the %System.OBJ ExportJava method from Caché Terminal:

USER> Do $SYSTEM.OBJ.ExportJava("CacheClassName","DirectoryName")

2. Add a Projection attribute the Caché class. The Caché Java Class Generator creates aprojection for the class each time that you compile the Caché class.

Here is the procedure for adding a Java Projection attribute to a Caché class:

1. Open the class in Caché Studio.

2. Click Class —> Add —> New Projection on the menu bar.

Lab Book: Java Projections                                                                                                                   9

Creating Projections

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3. Enter a name for the projection, for example JavaProjection. Click Next.

4. Select a Projection Type. Click %Projection.Java on the drop-down list.

5. Enter a value for the projection's ROOTDIR parameter, for example, c:\projections. Cachéplaces the generated projection in this directory. Click Finish.

6. The Class Editor adds the following declaration to the JavaTutorial.Contact definition:

Projection JavaProjection As %Projection.Java(ROOTDIR = "c:\projections");

Note: You can create projections for an entire package of Caché classes using:$System.OBJ.ExportJavaPackage("PackageName","DirectoryName").

1.10 Projection Details: Identifiers and DataTypes

The names of Caché class elements correspond fairly closely to the names of their Java pro-jections. The following table describes some of the potential differences:

Mappings: Caché Identifiers to Java Identifiers

Java ProjectionCaché Class

In general, projections preserve Caché package names. Exceptions:“%” symbols are replaced with “_” , and the Caché %Library

package becomes com.intersys.objects.

Package Names

Projections contain accessor methods for the Caché properties:getPropertyName and setPropertyName.

Property Names

In general, projections preserve class and method names.Exceptions: leading “%” symbols are replaced with “sys_” ; if thename is a Java reserved word, “_” is prepended to the name; fornames of methods and classes of the %Library package, the leading“%” is replaced with “_” and the first letter is converted to lowercase.

Class and MethodNames

In general, projections preserve variable names. Exceptions: leading“%” symbols are replaced by “_” and if a name is a Java reservedword a “_” is prepended to the name.

Variable Names

10                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Caché Java Class Generator projects Caché data types to Java data types according tothe CLIENTDATATYPE attribute of the Caché data type class. The following table describesseveral of the mappings:

Mappings: Caché Datatypes to Java Datatypes

Java Data TypeCLIENTDATATYPECaché Data Type

java.lang.StringVARCHAR%String

java.lang.StringVARCHAR%Name

java.lang.IntegerINTEGER%Integer

java.lang.DoubleDOUBLE%Float

java.sql.DateDATE%Date

Note: For the complete list of mappings between Caché data types and Java data types,see The Caché Java Projection in Using Java with Caché.

1.11 Projection Details: Collections

The following table describes the default projections for the three principal Caché Collectiontypes:

Lab Book: Java Projections                                                                                                                 11

Projection Details: Collections

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Mappings: Caché Collections to Java Collections

Projection TypeCollection Type

java.util.MapArrays

• %Library.ArrayOfDataTypes

• %Library.ArrayOfObjects

java.util.ListLists

• %Library.ListOfDataTypes

• %Library.ListOfObjects

com.intersys.classes.RelationshipObject

Note that this class implements the java.util.Map interface. Italso provides the asList method that returns a java.util.List

representation.

%Library.RelationshipObject

1.12 Projection Details: /NEWCOLLECTIONSFlag

Caché 5.2 provides the /NEWCOLLECTIONS flag to control the projection of collectionproperties. When /NEWCOLLECTIONS is set to 1, the default value in Caché 5.2, collectionproperties project to Java using the above mapping. You can set the flag either when defininga Projection within the class or when using $System.OBJ.ExportJava. Here is an example:

USER>Do $SYSTEM.OBJ.ExportJava("CacheClassName","DirectoryName","/NEWCOLLECTIONS=1")

If you set /NEWCOLLECTIONS=0, then collection properties project in the following way:

12                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Mappings: Caché Collection to Java Collections (/NEWCOLLECTIONS=0)

Projection Type (/NEWCOLLECTIONS=0). All types are dep-recated.

Caché Collection Type

Arrays • com.intersys.classes.ArrayOfDataTypes

• %Library.ArrayOfDataTypes • com.intersys.classes.ArrayOfObjects

• %Library.ArrayOfObjectsBoth types implement java.util.Map. Use this interface withobjects of these types.

Lists • com.intersys.classes.ListOfDataTypes

• %Library.ListOfDataTypes • com.intersys.classes.ListOfObject

• %Library.ListOfObjectsBoth types implement java.util.List. Use this interface withobjects of these types.

Note that the /NEWCOLLECTIONS flag applies only to collection properties. It does not applyto method return types. The projected return type of a Caché method that returns a collectionis one of the above deprecated types. There is no way to change this behavior.

1.13 Projection Details: Queries

Caché Java Projections provide resources for executing both Caché class queries as well asdynamic queries.

Lab Book: Java Projections                                                                                                                 13

Projection Details: Queries

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Caché Query Types

Java Client AccessCaché QueryType

Execute using a com.intersys.objects.CacheQuery object's execute method.The method returns a java.sql.ResultSet object to the client.

The Java Projection for a class containing a class query contains amethod, named query_<QueryName>, that returns an initializedCacheQuery object.

Alternatively, the Java client can create a new CacheQuery object usinga constructor and initialize it using the name of the class query.

Class Queries

Use the com.intersys.objects.Database openByQuery method. Pass theSQL string to the method. The method returns a java.util.Iterator objectcontaining a set of opened objects. Note that the SQL string must meetcertain requirements. See the Java documentation for details.

Alternatively, initialize a com.intersys.objects.CacheQuery object with theSQL string. Use execute to execute the query. The method returns astandard java.sql.ResultSet object.

Dynamic SQL

1.14 Projection Details: Persistent Classes

Persistent Caché classes have the ability to store themselves to the database. Java Projectionsof persistent Caché classes contain methods that can be used to manipulate persistent Cachéobjects. Using these methods you can do the following:

• Open a persistent object that is stored in the database. Doing this simultaneously opensthe Caché object on the server and its Java projection in the Java client.

• Update the persistent object's data and store the changes to the database.

• Remove a persistent object from the database.

The following table describes several of the methods supported by Java projections of persistentCaché objects. Note that all of the methods throw checked exceptions of type CacheException.

14                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Persistent Object Methods

DescriptionMethod

Opens the object with the specified id. Returns a instance of RegisteredObject

that can be cast to the correct type. Arguments include:_open

• db

• id

• concurrency — optional.

Saves the object to the database.save

Deletes the object with the specified object ID from the database. Argumentsinclude:

_deleteId

• db

• id

• concurrency — optional.

Returns a Boolean true if the object of the current type with the specifiedobject ID exists in the database. Returns false otherwise. Arguments include:

_existsId

• db

• id

1.15 Quiz Two

Question 1: Which one of the following Caché ObjectScript commands creates a Java Projec-tion for the class named CacheClass and stores it in the directory named dir?

1. Do $System.OBJ.ExportJava(CacheClass,dir).

2. Do $System.OBJ.ProjectToJava(CacheClass,dir)

3. Do $System.LoadJava(CacheClass,dir)

4. Do $System.DoJavaProjection(CacheClass,dir)

5. Do $System.CreateJavaProjection(CacheClass,dir)

Lab Book: Java Projections                                                                                                                 15

Quiz Two

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Question 2: A Caché property of type %Integer projects by default to which of the followingJava types?

1. int

2. long

3. java.lang.Integer

4. java.lang.Long

5. java.lang.String

Question 3: A Caché collection of type %ArrayOfObjects projects by default to which of thefollowing Java types?

1. java.util.Map

2. java.util.List

3. java.util.Vector

4. java.util.ArrayList

5. Object[]

1.16 Establishing a Connection: Full and Light

In order to use the Caché Java Binding, a Java application must first establish a connectionto Caché. Use the com.intersys.objects.CacheDatabase interface for this. Here are the steps:

1. Import the com.intersys.objects package:

import com.intersys.objects.*;

2. Declare and initialize variables used for establishing the connection:

Database dbconnection = null;String url="jdbc:Cache://localhost:1972/<Namespace>";String username=<User>;String password=<pwd>;

3. Connect using the Database getDatabase method to use the full binding. Note that themethod throws an exception of type CacheException.

16                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

try {db = CacheDatabase.getDatabase(url, username, password);}catch(CacheException ex){ }

4. Connect using the Database getLightDatabase method to use the light binding:

try {db = CacheDatabase.getLightDatabase(url, username, password);}catch(CacheException ex){ }

1.17 Opening an Existing Object

Here are the steps for opening an existing object and retrieving some property values:

1. Declare and initialize some variables:

Sample.Person person = null;Sample.Address addr = null;Id id = null;

2. Initialize a new Id object with a valid object id:

id = new Id(1);

3. Verify that an object with the specified object ID exists in the database:

if (!(Sample.Person.exists (db, id))){ System.out.println ("There is no Person with id " + id + " in the database."); db.close(); return; }

4. Open the object with the specified object id:

person = (Sample.Person) Sample.Person._open( db, id );

5. Retrieve some simple properties:

System.out.println( "ID: " + person.getId() );System.out.println( "Name: " + person.getName() );

6. Attempt to retrieve an embedded object and display some of its properties:

Lab Book: Java Projections                                                                                                                 17

Opening an Existing Object

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

addr = person.getHome();System.out.println( "Street: " + addr.getStreet() );System.out.println( "City: " + addr.getCity() );

7. Close the object and the database connection:

db.closeObject(person.getOref());person = null;db.close();

Note: Starting with step three above, the binding methods all throw exceptions of typeCacheException. For the sake of clarity, these code excerpts and the following donot include the try catch blocks.

1.18 Creating a New Object

Here are the steps for creating a new object, assigning some property values, and then savingthe object to the database.

1. Create the new instance using the constructor:

person = new Sample.Person(db)

2. Assign property values using the set methods:

person.setName("Doe, Joe A");

3. Save the instance and then retrieve its object id:

person.save();System.out.println ("Saved id: " + person.getId());

4. Close the object. Note that the proper way to close an object is to use the CloseObjectmethod of CacheDatabase. Each object supports a _close method, however this methodis deprecated and should not be used.

db.closeObject(person.getOref());person = null;db.close();

Close the database connection.

18                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

db.close()

1.19 Using Collections

Here are the steps for retrieving a list from Caché and manipulating its data:

1. Declare a variable to hold the list and the person:

Sample.Person person = null;java.util.List colors = null;

2. Retrieve the Person object and then its list. Iterate through the list:

person = (Sample.Person) Sample.Person._open( db, id);colors = person.getFavoriteColors();for (r = 0; r < colors.size(); r++) { System.out.println(" Element #" + r + " -> " + colors.get(r));}

3. Remove the first element and then add a new element:

if (colors.size() > 0) colors.remove(0);colors.add("Red");

4. Save the Person object. This saves the changes to the list to the database.

person.save()

5. Close the objects and the database connection:

db.closeObject(person.getOref());person = null;db.close();

Note: Caché arrays project to java.util.Map objects. Use this interface to manipulate them.

Lab Book: Java Projections                                                                                                                 19

Using Collections

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.20 Using a Relationship

Here are the steps for manipulating a Caché Relationship collection. In the example, there isa one-to-many relationship between Company and Employee. In addition, Employee is asubclass of Person.

1. Open an existing Employee object. Note that the object ID must be the ID of an Employee

object, because Person instances are not also Employee instances.

Sample.Employee employee = (Sample.Employee) Sample.Person._open( db, id);

2. From an Employee instance (the many-side of the relationship), you can get a referenceto its Company instance (the one-side of the relationship):

Sample.Company company = employee.getCompany();

3. Using the Company object, you can retrieve the collection of all its related Employee

instances. These instances are stored in a com.intersys.classes.RelationshipObject instance.This class implements java.util.Map. The code excerpt uses this interface. Note thatRelationshipObject supports the asList method that returns a java.util.List representationof the collection.

java.util.Map colleagues = company.getEmployees();System.out.println("Colleagues: ");for (java.util.Iterator it = colleagues.values().iterator(); it.hasNext();){ System.out.println("\t" + ((Sample.Person)it.next()).getName()); }

4. Close the object and the connection:

db.closeObject(employee.getOref());employee = null;db.close();

1.21 Quiz Three

Question 1: Which TWO of the following Java statements creates acom.intersys.objects.Database object? Assume that url, username, and password are variablesof type java.lang.String.

20                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1. Database db = new Database(url,username,password);

2. Database db = new LightDatabase(url,username,password);

3. Database db = CacheDatabase.getDatabase(url,username,password);

4. Database db = CacheDatabase.getFullDatabase(url,username,password);

5. Database db = CacheDatabase.getLightDatabase(url,username,password);

Question 2: Which ONE of the following Java statements opens both an existing persistentobject on the Caché Server and its corresponding Java proxy object? Assume that db refersto an appropriately initialized Database object and that id refers to the object ID of anexisting persistent Caché object.

1. Sample.Contact con = (Sample.Contact)db._open(id);

2. Sample.Contact con = (Sample.Contact)CacheDatabase._open(db,id);

3. Sample.Contact con = (Sample.Contact)Sample.Contact._open(db,id);

4. Sample.Contact con = new Sample.Contact(db,id);

5. S a m p l e . C o n t a c t c o n =

(Sample.Contact)Sample.Contact.getInstance(db,id);

Question 3: Assume that there is a parent-child relationship between the Caché classesSample.Contact and Sample.PhoneNumber and that the PhoneNumbers property representsthe collection of Sample.PhoneNumber objects within Sample.Contact. Assume also thatcontact is a Java variable referring to an instance of a Java projection of Sample.Contact.Which one of the following Java statements retrieves the Java projection of PhoneNumbers

from contact?

1. java.util.Map phoneNumbers = contact.PhoneNumbers();

2. java.util.Map phoneNumbers = contact.getPhoneNumbers();

3. java.util.List phoneNumbers = contact.PhoneNumbers();

4. java.util.List phoneNumbers = contact.getPhoneNumbers();

5. Sample.PhoneNumber[] phoneNumbers = contact.PhoneNumbers();

Lab Book: Java Projections                                                                                                                 21

Quiz Three

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.22 Overview: Caché JDBC

Caché 5.2 provides a high-performance Level 4 JDBC database driver. It is pure Java andinvolves no Caché-specific binary code and no JDBC-ODBC bridge. The driver supports theJDBC 3.0 API and includes the following features:

1. DriverManager and CacheDatabase Connections.

2. Dynamic SQL Select and Insert Statements.

3. Stored Procedure Execution.

4. Connection pooling.

5. Scrollable and updatable result sets.

6. Retrieval of automatically generated keys.

7. Multiple result sets from a single stored procedure.

This section begins by presenting a QuickStart guide for connecting to Caché and executinga dynamic SQL SELECT statement. The section then describes general information aboutthe Caché JDBC driver and then covers topics 1–2. The Advanced Features section coverstopics 4–7.

1.23 Caché JDBC Quick Start

Here are the basic steps for connecting a Java application to Caché using the Caché JDBCdriver and executing an SQL SELECT command:

1. Ensure that CacheDB.jar is on your class path. The file is in<cachesys>\Dev\java\Lib\JDK14.

2. Add the following code to your application:

Create the variables containing the connection string information:

String url = "jdbc:Cache://127.0.0.1:1972/<Namespace>";String user = <User>;String password = "<Pwd>;

Load the Caché JDBC driver and create the connection:

22                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Class.forName ("com.intersys.jdbc.CacheDriver");Connection dbconnection = DriverManager.getConnection(url,user,password);

Create the SELECT SQL and the java.sql.Statement object:

String stQuery = "Select * from Sample.Person";Statement stmt = dbconnection.createStatement();

Execute the query. Note that you should use the fully qualified java.sql.ResultSet class-name.

java.sql.ResultSet rs = stmt.executeQuery(stQuery);

Retrieve the query results:

int colnum = rsmd.getColumnCount();while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); } System.out.println(); }

Close the database connection:

dbconnection.close();

Note: Note that the above methods throw exceptions of type java.sql.SQLException andjava.lang.ClassNotFoundException that need to be handled.

1.24 JDBC Components and Resources

Here is the main component needed to use the Caché JDBC Driver:

• CacheDB.jar — Two different versions. One is located in <cachesys>\dev\java\lib\JDK14.Use this if you are using Java 1.4.x. Another version is located in<cachesys>\dev\java\lib\JDK15. Use this version if you are using Java 1.5.x. The jar filescontain the Caché JDBC driver as well as packages of classes used with the Caché JavaBinding Mechanism. Note that the archive must be on your application's class path.

In addition to these components, a standard Caché installation contains a number of otherresources to help you use the Caché JDBC Driver:

Lab Book: Java Projections                                                                                                                 23

JDBC Components and Resources

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• “JavaDoc” style class documentation for the packages in CacheDB.jar. This documentationis in <cachesys>\Dev\java\doc.

• A set of sample Java programs that demonstrate the use of the Java Binding to connectto Caché, open existing objects, create new objects, save object changes to Caché andexecute queries against Caché. These sample programs are in <cachesys>\dev\java\samples.

• Caché documentation: See Using Java with Caché within the Caché Language Bindingssection of the Caché documentation.

• Tutorials: See Caché with Java and J2EE QuickStart Tutorial inside the Caché Tutorialssection of the Caché documentation.

1.25 Connection Options

The Caché JDBC driver supports two different mechanisms for connecting a Java applicationto Caché.

1. Use java.sql.DriverManager to load the driver and then create the connection. This is thestandard Java technique for connecting to a database and it is fully supported by Caché.

2. Use com.intersys.objects.CacheDatabase to create the connection. The GetDatabasemethod returns a Database object that represents a connection. You must connect in thismanner when using the Java Binding. You can also connect in this manner when usingstandard JDBC. Database provides methods for creating PreparedStatement, andCallableStatement objects.

1.26 Connecting Using DriverManager

Here are the steps for using DriverManager:

1. Import the java.sql package:

import java.sql.*;

2. Create a connection string and declare some variables. The url should include the Cachéaddress and port along with the namespace name.

24                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

String url = "jdbc:Cache://127.0.0.1:1972" + "/<Namespace>";String user = <User>;String password = <Pwd>;

3. Use DriverManager to load the driver and create the connection:

try{Class.forName ("com.intersys.jdbc.CacheDriver");Connection dbconnection = DriverManager.getConnection(url,user,password);}

4. Create a java.sql.Statement using the connection. The Statement object can be used toexecute queries.

Statement stmt = dbconnection.createStatement()

5. Catch the exceptions thrown by the above methods:

catch (SQLException e){System.out.println(e.getMessage());}catch (ClassNotFoundException e){System.out.println(e.getMessage());}

1.27 Connecting Using CacheDatabase

Here are the steps for connecting to Caché using com.intersy.objects.CacheDatabase:

1. Import both the java.sql package and the com.intersys.objects package:

import java.sql.*;import com.intersys.objects.*;

2. Create a connection string and declare some variables. The url should include the Cachéaddress and port along with the namespace name.

String url = "jdbc:Cache://127.0.0.1:1972" + "/<Namespace>";String user = <User>;String password = <Pwd>;

3. Create a Database object using CacheDatabase:

Lab Book: Java Projections                                                                                                                 25

Connecting Using CacheDatabase

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

try{Database db = CacheDatabase.getDatabase(url, user, password);}

4. Use the Database object to create a Statement object for executing queries:

try{Statement stmt = db.createStatement();}

5. Both of the above methods throw exceptions of type CacheException:

catch(CacheException e){System.out.println(e.getMessage());}

1.28 Executing a SELECT

Here are the steps for executing an SQL SELECT on Caché using Statement:

1. Create a string containing the query:

String stQuery="SELECT ID, Name from Sample.Person";

2. Execute the query using the java.sql.Statement execute method. Note that you shouldalways use the fully qualified name java.sql.ResultSet to avoid clashes withcom.intersys.classes.ResultSet:

java.sql.ResultSet rs = stmt.executeQuery(stQuery);

3. Process the query results in the usual way:

ResultSetMetaData rsmd = rs.getMetaData();int colnum = rsmd.getColumnCount(); while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); } System.out.println();}

4. Close the result set and the database connection:

rs.close();dbconnection.close();

26                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Note: Several of the above methods throw exceptions of type SQLException. The requiredtry catch blocks are omitted for clarity. The examples on following pages omit thetry catch blocks as well.

1.29 Executing an INSERT

Here are the steps for executing an SQL INSERT on Caché using PreparedStatement:

1. Assign values to be inserted to variables and create the SQL string:

String name="Smith,John";String SSN=generateSSN();String age="35";String sql="INSERT INTO Sample.Person (Name,SSN,Age) " + "VALUES(?,?,?)";

2. Create the PreparedStatement object. Initialize it with the SQL string. If you want toretrieve any auto-generated keys, for example Caché object ids, initialize it with theStatement.RETURN_GENERATED_KEYS constant as well.

PreparedStatement pstmt = dbconnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

3. Set the values for the query parameters and execute the query:

pstmt.setString(1,name);pstmt.setString(2,SSN);pstmt.setString(3,age);pstmt.executeUpdate();

4. Close the database connection:

dbconnection.close();

1.30 Quiz Four

Question 1: Which one of the following must be on your Java application's class path whenusing the Caché 5.2 JDBC Driver?

1. <cachesys>\dev\java\lib\JDK14

Lab Book: Java Projections                                                                                                                 27

Executing an INSERT

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

2. CacheDB.jar

3. CacheBinding.jar

4. CacheObject.dll

5. The Caché Object Server

Question 2: Which one of the following Java statements creates a java.sql.Statement objectthat can be used to query Caché? Assume that db represents a properly instantiatedcom.intersys.objects.Database object.

1. Statement statement = new Statement(db);

2. Statement statement = new CacheStatement(db);

3. Statement statement = db.createStatement();

4. Statement statement = Connection.createStatement(db);

5. Statement statement = CacheDatabase.createStatement(db);

Question 3: Which of the following is the Caché JDBC driver name to use when connectingto Caché using DriverManager?

1. com.intersys.jdbc.Driver

2. com.intersys.jdbc.CacheDriver

3. com.intersys.objects.jdbc.Driver

4. com.intersys.objects.CacheDriver

5. com.intersys.objects.jdbc.CacheDriver

1.31 Caché Custom JSP Tag Overview

Caché 5.2 provides a library of custom JSP tags to use with Java Web applications. Thesetags provide easy access to Caché data from within JSP pages. They are especially useful forrapid prototyping. The actions supported by Caché custom JSP tags include:

• Connecting to Caché.

• Creating a new persistent object.

• Displaying the content of a persistent object.

28                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• Editing the property values of a persistent object.

• Generate HTML select (drop-down list, multiple-selection list) elements. The valuesdisplayed in the list correspond to possible Caché property values.

• Generate SQL Select queries using values selected in drop-down or multiple-selectionlists as parameter values.

The Caché custom tag library has been tested with the Tomcat version 4.1 and 4.0 JSP engines.

Note: For more information on JSP see the Sun Microsystems The J2EE Tutorial especiallythe JavaServer Pages Technology section. For more information on custom JSP tagssee Custom Tags in JSP Pages.

1.32 Caché Custom Tag Resources

Caché 5.2 provides the following components to support the custom tag library:

• CacheDB.jar — Located in <cachesys>\Dev\java\lib, this archive contains the tag handlers— the Java classes that implement the tag functionality. You must place CacheDB.jar onTomcat's class path. Here are two ways to do this:

1. Place CacheDB.jar in <TOMCAT_HOME>\common\lib and restart Tomcat.

2. Place CacheDB.jar in the WEB-INF\lib subdirectory of your application's directory.

• cache.tld — The tag library descriptor for the Caché custom tags. This file is in<cachesys>\Dev\java\lib\samples\jsp\WEB-INF. You must place cache.tld in the WEB-INF

subdirectory of your application's directory. You must also place a taglib directive refer-encing cache.tld in any JSP using a Caché custom tage. The directive should look likethe following:

<%@ taglib uri="/cache" prefix="cache" %>

• web.xml — A deployment descriptor for the sample application. The file is in<cachesys>\Dev\lib\java\samples\jsp\WEB-INF. It contains a <tag-lib> element specifyingthe uri and physical location of the tag library descriptor. You must place an analogous<tag-lib> element in the web.xml file for any of your Web applications that use the Cachécustom tag library.

In addition, Caché 5.2 includes the following resources to help you use the custom tag library:

Lab Book: Java Projections                                                                                                                 29

Caché Custom Tag Resources

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• A sample JSP application that demonstrates the use of the custom tags. This applicationis in <cachesys>\Dev\java\samples\jsp. The files WhatIsIt.txt and HowToSetup.txt provideoverviews of the tag library and installation instructions for the sample application.

• JavaDoc style API documentation for the com.intersys.jsp package. The classes in thispackage implement the tag handlers for the custom tags. The documentation is in<cachesys>\Dev\java\doc.

1.33 Installing and Executing the Samples

There are two options for installing and executing the JSP example application:

1. Add a <Context> element to your Tomcat installation's server.xml file. This file is in<TOMCAT_HOME>\conf. Here is the element to add:

<Context path="/cache" docBase="<cachesys>/Dev/Java/samples/jsp" crossContext="true" debug="5" reloadable="true" > <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_cache_log." suffix=".txt" timestamp="true"/> </Context>

Note that the value of the docBase attribute should be the path, either relative or absolute,to the directory containing the sample application. Place the <Context> element immedi-ately after the existing <Context> elements and before the closing <Host> tag in server.xml.Execute the application by opening http://localhost:8080/cache in a Web browser.

2. Copy the application files into a subdirectory of <TOMCAT_HOME>\webapps. ShutdownTomcat. Create <TOMCAT_HOME>\webapps\cache. Copy all of the .jsp files and theWEB-INF directory and its contents from <cachesys>\Dev\Java\Samples\JSP to the newdirectory. Restart Tomcat. Execute the application by opening http://localhost:8080/cache

in a Web browser.

Note: Both 1 and 2 assume that you have placed CacheDB.jar on Tomcat's class path. SeeCaché Custom Tag Resources in this document for instructions.

30                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.34 Some Caché Custom Tags and theirAttributes

The following table describes some of the Caché custom JSP tags and their attributes.

Some Custom Tags

DescriptionTag

Creates a connection to Caché.<connect>

Closes the connection to Caché.<disconnect>

Displays the contents of an object. Optionally, allows updating the con-tent.

<dump>

Creates an HTML form that can be used to create a new object and setits property values.

<new>

Creates an HTML form that can be used to set an object property value.<set>

1.35 The <list> Tag

The <list> tag creates an HTML SELECT list (drop-down or multi-value) using the valuesof a field of the specified table (class). When the HTML form containing the SELECT elementis submitted, a query that uses the selected data as a parameter is executed.

Here are the database related atttributes of the <list> tag:

• table — The name of the Caché table (class).

• property — The property whose values populate the list. If the property is an objectproperty, then the value attribute of the generated <Option> tags will have object IDsas values.

• useHistory — Boolean. If true, then only the cached results of prior queries are queried.If false, the query is performed against the entire database table.

Here are some of the HTML related attributes of the <list> tag:

Lab Book: Java Projections                                                                                                                 31

Some Caché Custom Tags and their Attributes

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• multiple — Boolean. If true, multiple values can be selected. If false only a single valuecan be selected.

• name — The value becomes the value of the name attribute of the generated HTMLSELECT element.

• size — The size of the SELECT element.

• id — The ID value for the SELECT element.

• none — Boolean. If the value is true (default), then the “none” element is added to thelist. When the element is selected, submitting the form generates no query.

The <list> tag uses a query of the following form to populate the HTML Select elementthat it generates:

SELECT DISTINCT <Property> FROM <Table or View Name> ORDER BY <Property>

1.36 Using Custom Tags

The following JSP page, listNames.jsp, uses the <connect> tag to connect to Caché and thenthe <list> tag to display the Name field for each row of the Sample.Employee table:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Table Content</title> <%@ taglib uri="/cache" prefix="cache" %> </head> <body> <cache:connect namespace=<Namespace> user=<User> password=<Pwd>/> <form method = "GET" name = "myForm" action="view.jsp"> <cache:list table="Sample.Person" property="Name" size = "10" useHistory = "false" multiple = "false" none="false" forceselection="true">

</cache:list> <input name="find" type="submit" value="View Selected" align="middle" style="font-family: Arial, Times New Roman; font-size: medium"> </form> <hr> </body></html>

32                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.37 Quiz Five

Question 1: Which one of the following must be on Tomcat's class path when using the Caché5.2 Custom JSP Tag Library?

1. <cachesys>\dev\java\lib\JDK14

2. CacheDB.jar

3. CacheBinding.jar

4. CacheObject.dll

5. The Caché Object Server

Question 2: What is the name of the tag library descriptor for the Caché Custom JSP taglibrary provided with Caché 5.2?

1. tags.tld

2. cache.tld

3. cachetags.tld

4. web.xml

5. cache.xml

Question 3: What is the package name for Caché Custom Tag Library tag handlers?

1. com.intersys.jsp

2. com.intersys.tags

3. com.intersys.jdbc

4. com.intersys.objects

5. com.intersys.classes

Lab Book: Java Projections                                                                                                                 33

Quiz Five

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1.38 Design Considerations: Java Binding orJDBC?

You have the choice of connecting your Java application to Caché using either the JavaBinding mechanism or standard relational JDBC. You can of course use both modes in asingle application. The primary factors for choosing between the connection modes include:application efficiency and development (and maintenance) efficiency.

1. Application Efficiency: JDBC provides the most efficient solution for retrieving andupdating database information. The light Java Binding, however, nearly matches theefficiency of JDBC.

2. Development (maintenance) Efficiency: The Java Binding mechanism allows an applica-tion to be fully object-oriented from the front end through to the database. By contrast,JDBC requires that the application translate between the relational representation of thedata provided by the JDBC result set and the object-oriented representation required bythe application. Removing this difficult and error prone translation step can greatlyincrease development and maintenance efficiency.

You should also remember that the light Java binding provides an excellent compromise. Itprovides efficiency that rivals JDBC yet allows for a fully object-oriented application design.With the light binding you can do all of the following:

1. Open existing objects and create new objects.

2. Set the properties of objects.

3. Save object changes to the database.

4. Execute Caché methods with some restrictions.

The only limitation of the light binding with respect to the full binding is that the light bindingcannot execute Caché instance methods that return objects.

34                                                                                                                 Lab Book: Java Projections

The Basics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

2Lab Project

2.1 Project Overview

This section presents a series of lab projects that involve connecting Java applications to theCaché Foreign Cash Exchange (FCE) Caché application built in the Foundation I course.The projects simulate the implementations of several use cases for FCE. For example, oneproject simulates an ATM that a customer can use to perform a currency exchange with theFCE system. Your task is to design and build the Java application and connect it to FCE usingthe Java Binding, JDBC, or a combination of the two.

In addition to the project descriptions, we have provided the following resources to help youcomplete the projects:

• Sample Solutions, both Swing and Web-based, for Project One. See the appendix formore information on these sample solutions.

• Skeleton code, both Swing and Web-based, for Project One. See the appendix for detailedinstructions on how to complete the skeleton code.

2.2 Project One: Currency Order through anATM

The first project is to create a Java application (either Swing or Web-based) that simulates acash exchange ATM for the Caché Foreign Cash Exchange application. The simulator allows

Lab Book: Java Projections                                                                                                                 35

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

customers to perform a cash exchange using one of the system's ATMs. Here is the processthat should be supported by the system:

Project One: Basic Functionality — Cash Payments Only

1. The simulator displays the list of the FCE ATMs.

2. The user selects an ATM.

3. The simulator displays the currencies supported by the ATM selected by the user.

4. The user previews a currency order. The user specifies the requested currency (the currencythe user wants), the supplied currency (the currency the user has) and the supplied amount(the amount of the supplied currency to exchange).

5. The simulator displays the fee, exchange rate, and amount of the requested currency thatwould be returned to the user in the prospective transaction. Note for Project One thepayments are cash only. Credit card and customer account payments for currencyexchanges are not supported.

6. The user submits the currency order. The selected ATM determines whether or not it canprocess the order.

7. If the ATM is able to process the order, the application processes the currency order.

8. If the ATM is unable to process the order, the currency order is not processed. Theapplication notifies the customer that the currency order was rejected.

Project One does not involve credit card or customer account payments. Users do not needto log on and no account balances need to be updated.

Note: The appendix describes how to install and execute a sample solution for this project.It also describes a set of starter files that you can use to complete the project, if youchoose.

2.3 Project Two: Credit Card and CustomerAccount Payments

Project Two: Add Credit Card and Customer Account Payments

For Project Two add the following functionality to the completed Project One application:

36                                                                                                                 Lab Book: Java Projections

Lab Project

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1. Users can pay for their cash exchanges using credit cards. The users enters the card typeand number. This information is recorded by the system when it process the currencyorder.

2. Users can pay for cash exchanges using their accounts with the system. The user entersname and password information into the system.

• The simulator verifies that the account information is valid.

• The simulator determines the currency type for the account. This determines thesupplied currency type for the cash exchange.

• When the simulator attempts to process the order, it must verify both that the ATMhas sufficient funds of the requested currency type and that the user account hassufficient funds of the supplied currency type.

Lab Book: Java Projections                                                                                                                 37

Project Two: Credit Card and Customer Account Payments

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3Advanced Topics

3.1 Overview

This section presents additional features of both the Caché Java Binding and JDBC supportthat are not covered in The Basics.

3.2 Overview: Caché Java Binding AdvancedFeatures

This section describes how to do the following using the Caché Java Binding:

• Execute both class queries and dynamic queries.

• Open a set of objects simultaneously using openByQuery.

• Bind to Caché objects dynamically.

• Perform batch inserts.

• Use transactions.

Lab Book: Java Projections                                                                                                                 39

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3.3 Using a Class Query

Here are the steps for using the com.intersys.objects.CacheQuery class to execute a classquery. The Sample.Person class contains the ByName query. This query accepts a singlestring representing a name as a parameter. The query retrieves the object id, Name, DOB, andSSN for each Sample.Person instance whose Name value matches the parameter value.

1. Create a CacheQuery instance. Initialize it with the name of the class: Sample.Person

and the name of the query: ByName.

CacheQuery cq = new CacheQuery( db, "Sample.Person", "ByName" );

Note that db is a Database instance.

2. Use execute to execute the query. The method returns a java.sql.ResultSet instance. Notethat the com.intersys.classes package contains a ResultSet class as well. Use the fullyqualified name: java.sql.ResultSet, to prevent name clashes.

java.sql.ResultSet rs = cq.execute();

3. Iterate through the result set and display the query results:

while (rs.next()) { String s = ""; for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (s.length() > 0) { s += ": "; } s += rs.getString( i ); } System.out.println( s );}

4. Close the result set and the database connection:

rs.close();db.close();

3.4 Using a Dynamic Query

Here are the steps for executing a dynamic query using com.intersys.classes.CacheQuery:

40                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

1. Create a string containing an SQL statement:

String sql = "SELECT ID, Name, DOB, SSN FROM Sample.Person WHERE Name %STARTSWITH ?";

2. Create a CacheQuery object. Initialize it with the SQL string.

CacheQuery cq = new CacheQuery( db, sql );

3. Use execute to execute the query. The query accepts a single string as a parameter. Themethod returns a java.sql.ResultSet object. Note that the com.intersys.classes packagecontains a ResultSet class as well. Use the fully qualified name: java.sql.ResultSet, toprevent name clashes.

String name = "";java.sql.ResultSet rs = cq.execute();

4. Iterate through the result set and display the query results:

while (rs.next()) { String s = ""; for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (s.length() > 0) { s += ": "; } s += rs.getString( i ); } System.out.println( s );}

5. Close the result set and the database connection:

rs.close();db.close();

3.5 Using OpenByQuery and a Simple Condition

Use com.intersys.objects.Database OpenByQuery to open instances of all objects of a partic-ular type that satisfy a condition. Specify the condition using SQL syntax. The condition mustbe simple and refer only to properties of a single class. It can include an “Order By” clause.For Sample.Person, valid conditions include:

• "Name %STARTSWITH 'A'"

Lab Book: Java Projections                                                                                                                 41

Using OpenByQuery and a Simple Condition

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• "Home_City = 'BOSTON'"

• "Home_City = 'BOSTON' ORDER BY Name"

Here are the steps:

1. Define a string containing the sql condition as well as an array containing any parametersfor the condition:

String sql = "Name %startsWith ?";String query = "A";String[] qargs = {query};

2. Execute openByQuery. Pass the method the name of the class, the condition, and theparameter array. Note that the method returns a java.util.Iterator for the collection ofopened objects created by the method.

java.util.Iterator people = db.openByQuery ("Sample.Person", sql, qargs);

3. Iterate through the collection displaying the properties of the objects:

while (people.hasNext()){ Sample.Person person = (Sample.Person) people.next(); System.out.print ("ID: " + person.getId() ); System.out.print ("\tName: " + person.getName() ); System.out.print ("\tSSN: " + person.getSSN() ); System.out.println("\tDOB: " + person.getDOB() );}

4. Close the database connection:

db.close();

3.6 Using OpenByQuery and a Complex Query

With OpenByQuery you can also execute a complex SQL query. The query must satisfy thefollowing conditions:

• The first returned column must be the fully qualified %ID column for the table. Forexample, when opening Sample.Person objects, the first column must be “Sample.Per-son.%ID” .

• Columns in an “Order By” clause must be specified by name and not number.

42                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Here are the steps:

1. Create a string containing the query to execute.

String sql = "SELECT Sample.Employee.%ID, Sample.Company.Name " + "from Sample.Employee, Sample.Company WHERE Sample.Employee.Company "+ " = Sample.Company.ID and Sample.Company.Name %StartsWith ?"+ " order by Sample.Company.Name";

2. Create an array of strings containing parameter values for the query.

String query = "B";String[] qargs = {query};

3. Execute OpenByQuery. Pass it the SQL and the parameter values.

java.util.Iterator people = db.openByQuery(sql, qargs);

4. Iterate through the collection of open objects retrieving their properties:

while (people.hasNext()){ Sample.Employee person = (Sample.Employee) people.next(); System.out.print ("ID: " + person.getId() ); System.out.print ("\tName: " + person.getName() ); System.out.println("\tCompany: " + person.getCompany().getName());}

5. Close the database connection:

db.close();

3.7 Calling By Reference and Output Arguments

Caché supports passing arguments by reference as well as defining arguments as outputparameters of a method. Java provides no direct support for either of these mechanisms.Moreover, certain Java classes such as String, Double, Integer, and so on, are immutable. Thevalues that they hold cannot be changed. Java projections wrap arguments that are passed byreference or that are output parameters in special Holder classes. The server can update thevalues contained within these Holder classes and thereby simulate output parameters andpassing arguments by reference.

Here is an example of a Caché method, named AddOne, that accepts a single %Integer as anargument. The argument can be passed by reference to the method.

Lab Book: Java Projections                                                                                                                 43

Calling By Reference and Output Arguments

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

ClassMethod AddOne(ByRef X As %Integer) As %String{ Set X=X+1 Quit "Done"}

Here is the signature and return type of the Java projection for AddOne:

public static java.lang.String AddOne (com.intersys.objects.Database db, com.intersys.objects.IntegerHolder X) throws com.intersys.objects.CacheException

Notice that the projection of the “ByRef” argument is type IntegerHolder.

Here is a piece of Java code that uses the projection to invoke AddOne:

... IntegerHolder arg = new IntegerHolder(0); ByRefTest.AddOne(db,arg); int newValue=((Integer)arg.getValue()).intValue();

...

Note: The concrete implementations of Holder include BigDecimalHolder, BooleanHolder,ByteArrayHolder, DateHolder, DoubleHolder, and IntegerHolder. For the complete list,see the documentation for com.intersys.objects.Holder in the Java API documentationfor the Caché Java Binding.

3.8 Using Dynamic Binding

You can use the classes of the com.intersys.objects.reflect package to bind dynamically toCaché objects. The following code sample includes a method, showObject, that outputs thevalues of all of the properties of an object.

1. Import the needed packages and classes:

import com.intersys.objects.*;import com.intersys.objects.reflect.*;import com.intersys.classes.RegisteredObject;

2. Open the Sample.Person object with object ID 1. Next pass the object to showObject:

44                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

String classname="Sample.Person";CacheClass cacheClass = dbConnection.getCacheClass (className);Object obj = cacheClass.openObject (new Id(id));showObject(obj,"");

3. Here is the definition of showObject. It iterates through the all of the object's fields anddisplays the name of each along with its value. If the field value is itself an object, instanceof RegisteredObject, the method calls itself passing the object instance.

private static void showObject (Object obj, String ident) throws CacheException{ CacheClass realClass = ((RegisteredObject) obj).getCacheClass (); CacheField[] cFields = realClass.getFields (); for (int i = 0; i < cFields.length; i++) { CacheField cFld = cFields[i]; String fName = cFld.getName (); Object value = cFld.get(obj); if (value instanceof RegisteredObject){ System.out.println (ident + fName + ":"); showObject (value, ident + "\t"); } else { System.out.println (ident + fName + " = " + value); } }}

Note: The sample programs DynamicBindingSample.java andLightDynamicBindingSample.java provide more in depth examples of dynamic bindingincluding dynamic binding with the Light Java Binding. These programs are in<cachesys>\Dev\java\samples.

3.9 Using Batch Inserts

Java Projections provide methods for performing batch inserts. Note that the connectionobject used with batch insert methods is a java.sql.Connection object. Create this connectionusing the Caché JDBC driver. Here are the steps for doing a batch insert on Sample.Person:

1. Create the java.sql.Connection object:

Class.forName ("com.intersys.jdbc.CacheDriver");java.sql.Connection dbconnection = DriverManager.getConnection(url,username,password);

2. Use addToBatchInsert to create a row of data to be inserted into Sample.Person. Themethod returns an instance of Object representing the batch to which the data has been

Lab Book: Java Projections                                                                                                                 45

Using Batch Inserts

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

added. The first argument represents the “batch” . If the argument is null the methodcreates a new batch. Note that Name and SSN are required fields for Sample.Person sovalues must be provided for them.

String name = "Smith,John";String SSN = generateSSN();Object batch = Sample.Person.addToBatchInsert(null, dbconnection, null, new ArrayList(), name,SSN,null,null,null,null,null,null,null,null,null);

3. Add another set of data to the batch. This time use the batch created on the earlier lineas an argument to addToBatchInsert.

name = "Smith,Jane";SSN = generateSSN();Sample.Person.addToBatchInsert(batch, dbconnection, null, new ArrayList(), name,SSN,null,null,null,null,null,null,null,null,null);

4. Use executeBatchInsert to perform the batch insert. Note that the method returns a listcontaining the object IDs of the newly created objects.

java.util.List list = Sample.Person.executeBatchInsert(dbconnection, batch, 1);

Note: The above code example uses generateSSN. This method simply generates a randomSSN with the correct format "3N1""-""2N1""-""4N". See the sample programCJTest2.java in <cachesys>\Dev\java\samples.

3.10 Using Transactions

The com.intersys.objects.Database interface provides the following methods for transactionsupport:

DescriptionMethod

Starts a transactiontransactionStart

Commits a transactiontransactionCommit

Rolls back a transactiontransactionRollback

46                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The following code starts a transaction. It then opens, modifies, and saves an object. Finally,the code commits the transaction. The updates are saved in the database:

dbconnection.transactionStart(); if (id == null) id = new Id( 1 ); person = (Sample.Person) Sample.Person._open( dbconnection, id); person.setSSN(generateSSN()); person.save(); dbconnection.closeObject(person.getOref());dbconnection.transactionCommit();

The following code starts a transaction. It then opens, modifies, and saves an object. Finally,it rolls back the transaction. The updates to the objects are not saved in the database.

dbconnection.transactionStart(); if (id == null) id = new Id( 1 ); person = (Sample.Person) Sample.Person._open( dbconnection, id); person.setSSN(generateSSN()); person.save(); dbconnection.closeObject(person.getOref());dbconnection.transactionRollback();

3.11 Overview: JDBC Advanced Features

This section describes how to do the following using Caché and JDBC:

• Obtain database connections using a connection pool.

• Execute dynamic queries that use the Caché implicit join syntax.

• Use transactions.

• Automatically return the object ID values for newly inserted rows.

• Execute stored procedures.

• Execute a stored procedure that returns multiple result sets.

• Scrolling in and updating a result set.

Lab Book: Java Projections                                                                                                                 47

Overview: JDBC Advanced Features

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3.12 Using a Connection Pool

The com.intersys.jdbc.CacheConnectionPoolDataSource class implements thejavax.sql.ConnectionPoolDataSource interface providing a connection pool for your Java clientapplications. Here are the steps for using a connection pool to connect to Caché:

1. Import the needed packages:

import com.intersys.jdbc.*;import java.sql.*;

2. Create a database url and assign a valid user name and password to a pair of variables:

String url = "jdbc:Cache://127.0.0.1:" + port + "/<Namespace>;String user = <User>;String password = <Pwd>;

3. Instantiate CacheConnectionPoolDataSource object. Use the reStart method to close allof the physical connections and empty the pool. Use setURL to set the database url forthe pool's connections.

CacheConnectionPoolDataSource ds = new CacheConnectionPoolDataSource();ds.restartConnectionPool();ds.setURL( url);

4. Initially, getPoolCount returns 0.

System.out.println(ds.getPoolCount()); //outputs 0.

5. Use getConnection to retrieve a database connection from the pool.

Connection dbConnection = ds.getConnection(user,password);

6. Close the connection. Now getPoolCount returns 1.

dbConnection.close();System.out.println(ds.getPoolCount()); //outputs 1

48                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3.13 Using Implicit Joins

Caché SQL supports an Implicit Join syntax, represented by the –> operator, that simplifiesthe SQL for certain types of joins. Use the –> operator whenever a table has a reference col-umn, that is, a column a containing the ID values of another table. In a Caché parent-childrelationship the table containing the child objects has a column that references the parenttable.

The following query returns the names of all employees whose name begins with “A” andworks for MacroCalc. The implicit join syntax can be used because the Sample.Employee

table references the Company table.

Select ID, Name from Sample.Employee Where Name %STARTSWITH 'A' and Company->Name %STARTSWITH 'MacroCalc'Order By Name

In the Java client you can use an implicit join query in the same way that you would use anyother query:

1. Create the string containing the query and use it to initialize the PreparedStatement object:

String sql= "Select ID, Name from Sample.Employee Where Name %STARTSWITH ?" + "and Company->Name %STARTSWITH ? Order By Name";PreparedStatement pstmt = dbconnection.prepareStatement(sql);

2. Set the values of the query parameters and execute the query:

pstmt.setString(1,"A");pstmt.setString(2,"MacroCalc");java.sql.ResultSet rs = pstmt.executeQuery();

3. Retrieve the query results in the usual fashion:

ResultSetMetaData rsmd = rs.getMetaData();int colnum = rsmd.getColumnCount();while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); } System.out.println();}

4. Close the result set and the database connection:

Lab Book: Java Projections                                                                                                                 49

Using Implicit Joins

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

rs.close();dbconnection.close();

3.14 JDBC Transaction API

The Caché JDBC driver supports the JDBC transaction API. Here are the java.sql.Connection

methods used for transaction handling:

DescriptionMethod

By default Connection objects are in autocommit mode. In thismode an SQL statement is committed as soon as it is exe-cuted. To group multiple SQL statements into a transaction,first use setAutoCommit(false) to take the Connection objectout of autocommit mode. Use setAutoCommit(true) toreset the Connection object to autocommit mode.

setAutoCommit

Executing commit commits all SQL statements executedsince the last execution of either commit or rollback.

commit

Executing rollback aborts a transaction and restores anyvalues changed by the transaction back to their original state.

rollback

Sets the isolation level for a transaction. Caché 5.2 supportsthe following JDBC transaction isolation levels:

setTransactionIsolation

• TRANSACTION_READ_UNCOMMITTED — Level 1. Permitsdirty reads as well as non-repeatable and phantom reads.

• TRANSACTION_READ_COMMITTED — Level 2. Preventsdirty reads, but allows non-repeatable and phantom reads.

getIsolationLevel

50                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3.15 Using JDBC Transactions

In order to group SQL statements into a transaction, you must first disable autocommit modeusing setAutoCommit:

dbconnection.setAutoCommit(false);

Use commit to commit to the database all SQL statements executed since the last executionof commit or rollback:

pstmt1.execute();pstmt2.execute();pstmt3.execute();dbconnection.commit();

Use rollback to roll back all of the transactions in a transactions. Here the rollback is invokedif an SQLException is thrown by any SQL statement in the transaction:

catch(SQLException ex){ if (dbconnection != null) { try { dbconnection.rollback(); } catch (SQLException excep){} }}

3.16 Retrieving Generated Keys

When you insert a new row into a table, Caché automatically generates an object ID for therow. Here are the steps for retrieving this value:

1. Initialize the PreparedStatement object with both the SQL string and theStatement.RETURN_GENERATED_KEYS constant:

PreparedStatement pstmt = dbconnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

2. After executing the update, retrieve the generated keys into a result set:

Lab Book: Java Projections                                                                                                                 51

Using JDBC Transactions

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

pstmt.executeUpdate();java.sql.ResultSet rs = pstmt.getGeneratedKeys();

3. Retrieve the contents of the result set in the normal fashion:

int colnum = rsmd.getColumnCount(); while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); } System.out.println(); }

4. Close the result set and database connection:

rs.close();dbconnection.close();

3.17 Executing a Stored Procedure

Here are the steps for executing a Caché stored procedure. Sample.Person contains a storedprocedure named ByName. Its SqlName is SP_Sample_By_Name. Refer to it by this namein the Java client code.

1. Create a java.sql.CallableStatement object. Initialize it with the name of the stored proce-dure.

CallableStatement cs = dbconnection.prepareCall("call Sample.SP_Sample_By_Name(?)");

2. Set the value of the query parameter and execute the query:

cs.setString(1,"A");java.sql.ResultSet rs = cs.executeQuery();

3. Iterate through the result set in the usual fashion:

ResultSetMetaData rsmd = rs.getMetaData();int colnum = rsmd.getColumnCount();while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); }System.out.println();}

52                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

4. Close the result set and the database connection:

rs.close();dbconnection.close();

3.18 Executing a Stored Procedure: MultipleResult Sets

Caché 5.2 allows you to define a stored procedure that returns multiple result sets. The Caché5.2 JDBC driver supports the execution of such stored procedures. Here is an example of aCaché stored procedure that returns two result sets. Note that the two query results have dif-ferent column structures:

ClassMethod DRS(start) [ ReturnResultsets, SqlProc ]{ $$$ResultSet("select Name from Sample.Person where Name %STARTSWITH :start Order By Name") $$$ResultSet("select Name, DOB from Sample.Person where Name %STARTSWITH :start Order By Name ") Quit}

This stored procedure is not defined in Sample.Person. In order to try this example, you mustfirst add the stored procedure to Sample.Person. In addition, you must add the followinginclude statement at the start of the file (outside of the class definition) containingSample.Person. Remember to recompile.

include %occResultSet

Here are the steps for executing the above stored procedure from a Java client and iteratingthrough both of the returned result sets:

1. Create the java.sql.CallableStatement object. Initialize it using the name of the storedprocedure. Set the query parameters and use execute to execute the query:

CallableStatement cs = dbconnection.prepareCall("call Sample.Person_DRS(?)");cs.setString(1,"A");boolean success=cs.execute();

Lab Book: Java Projections                                                                                                                 53

Executing a Stored Procedure: Multiple Result Sets

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

2. Iterate through the pair of result sets displaying the data. Note that getMoreResultsmoves to the Statement object's next result set while getResultSet retrieves the currentresult set.

if(success){ do{ java.sql.ResultSet rs = cs.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); for (int j=1; j<rsmd.getColumnCount() + 1; j++) { System.out.print(rsmd.getColumnName(j)+ "\t\t"); } System.out.println(); int colnum = rsmd.getColumnCount(); while (rs.next()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " \t "); } System.out.println(); } System.out.println(); }while (cs.getMoreResults());}

3. Close the database connection:

dbconnection.close();

Note: By default getMoreResults closes the current result set before moving to the next.The Caché JDBC Driver does not support keeping the current result set open aftermoving to the next.

3.19 Scrolling in a Result Set

The Caché 5.2 JDBC driver supports scrollable result sets. This means that Java applicationsare not restricted to moving only forward through a result set. Here are the steps for creatingand using a scrollable result set:

1. Create a Statement object. Initialize it with either ResultSet.SCROLL_TYPE_SENSITIVE

or ResultSet.SCROLL_TYPE_INSENSITIVE:

String sql="Select ID, Name, SSN from Sample.Person Where "+ "Name %STARTSWITH ? Order By Name";PreparedStatement pstmt = dbconnection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

2. Set the query parameters and execute the query in the usual fashion:

54                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

pstmt.setString(1,"A");java.sql.ResultSet rs = pstmt.executeQuery();

3. The application can scroll backwards as well as forwards through this result set. UseafterLast to move the result set's cursor to after the last row. Use rs.previous to scrollbackwards.

ResultSetMetaData rsmd = rs.getMetaData();rs.afterLast(); while (rs.previous()) { for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " "); } System.out.println(); }

4. Move to a specific row using absolute. This code displays the contents of the third row:

rs.absolute(3);for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " ");}

5. Move to a specific row relative to the current row using relative. The following codeagain displays the contents of the third row:

rs.first();rs.relative(2);for (int i=1; i<=colnum; i++) { System.out.print(rs.getString(i) + " ");}

6. Close the result set and the database connection:

rs.close();dbconnection.close();

Note: Initializing a result set with ResultSet.TYPE_SCROLL_SENSITIVE creates a resultset that is scrollable and displays changes made to the underlying data by othertransactions. Initializing with ResultSet.TYPE_SCROLL_INSENSITIVE creates aresult set that is scrollable, but does not display changes to the underlying data madeby other processes.

Lab Book: Java Projections                                                                                                                 55

Scrolling in a Result Set

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3.20 Updating a Result Set

The Caché 5.2 JDBC Driver also supports updatable result sets. A Java application can updatean open result set and these changes are saved to the database. Here are the steps:

1. Create a Statement object. Initialize it with an SQL string and theResultSet.CONCUR_UPDATABLE constant:

String sql="Select Name, SSN from Sample.Person "+ Where Name %STARTSWITH ? Order By Name"; PreparedStatement pstmt = dbconnection.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

2. Set the value of the query parameter and execute the query in the usual fashion:

pstmt.setString(1,"A");java.sql.ResultSet rs = pstmt.executeQuery();

3. To update a row, move the cursor to that row and update the correct columns and theninvoke updateRow:

rs.last();rs.updateString("Name", "Avery. Tara R");rs.updateRow();

4. To insert a row move the cursor to the “insert row” and then update that row's columns.Be sure that all non-nullable columns are updated. Finally, invoke insertRow:

rs.moveToInsertRow();rs.updateString(1, "Abelson,Alan");rs.updateString(2, generateSSN()); rs.insertRow();

Note: A result set that is going to have new rows inserted should not include the Caché IDcolumn. This column contains default values supplied by Caché.

The above code example uses generateSSN. This method simply generates a randomSSN with the correct format "3N1""-""2N1""-""4N". See the sample programCJTest2.java in <cachesys>\Dev\java\samples.

56                                                                                                                 Lab Book: Java Projections

Advanced Topics

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

AAnswers to Quiz Questions

Quiz One

• Question 1: CacheDB.jar.

• Question 2: The Light Binding provides greater efficiency, but less functionality thanthe Full Binding.

• Question 3: A Java class that serves as a proxy for a Caché class within a Java application.

Quiz Two

• Question 1: Do $System.OBJ.ExportJava(CacheClass,dir)

• Question 2: java.lang.Integer

• Question 3: java.util.Map

Quiz Three

• Q u e s t i o n 1 : D a t a b a s e d b =

CacheDatabase.getDatabase(url,username,password); and Database db =CacheDatabase.getLightDatabase(url,username,password);

• Q u e s t i o n 2 : S a m p l e . C o n t a c t c o n =

(Sample.Contact)Sample.Contact._open(db,id);

• Question 3: java.util.Map phoneNumbers = contact.getPhoneNumbers();

Quiz Four

• Question 1: CacheDB.jar

Lab Book: Java Projections                                                                                                                 57

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

• Question 2: Statement statement = db.createStatement();

• Question 3: com.intersys.jdbc.CacheDriver

Quiz Five

• Question 1: CacheDB.jar

• Question 2: cache.tld

• Question 3: com.intersys.jsp

58                                                                                                                 Lab Book: Java Projections

Answers to Quiz Questions

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

BSolutions for Project One

The lab book materials include both a Java Swing and a Web-based solution for Project One.These solutions are organized as NetBeans 5.0 projects. Use the instructions contained in theREADME.txt included with each solution to build and execute it using NetBeans. Each solutioncan also be imported into the IDE of your choice and executed. Alternatively, once built, theJava Swing solution can be executed from the command-line. Building the Web-based solutionproduces a WAR file that you can deploy manually to your application server.

The following files contain the solutions:

• FCESwingProj1Soln.zip — Swing solution for project one.

• FCEWebProj1Soln.zip — Web-based solution for project one.

Lab Book: Java Projections                                                                                                                 59

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

CStarter Files for Project One —Swing Version

FCESwingProj1Starter.zip contains a set of files to help you implement a Java Swing solutionfor Project One. The files are organized as a NetBeans 5.0 project. You can either open theproject in NetBeans or import them into your favorite IDE.

The starter files include a completed Swing GUI (userinterface\ProcessCurrencyOrderUI.java)as well as the skeleton code for the data access layer of the application(controller\CurrencyOrderController.java). You need only complete the methods incontroller\CurrencyOrderController.java to complete the application. See below for detaileddescriptions of the methods that you need to implement. Note that you can use either projec-tions or JDBC or a combination of the two to complete the project. FCESwingProj1Starter.zip

archive contains the following directories and files:

Lab Book: Java Projections                                                                                                                 61

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Project One Starter Files and Directories — Swing Version

FilesDirectory

src\controller 1. CurrencyOrderController.java — Contains the stub methods that youshould implement. See the list below.

src\userinterface 1. ProcessCurrencyOrderUI.java — Java source file containing the codefor the Swing GUI.

2. ProcessCurrencyOrderUI.form — XML file containing configurationinformation for the Swing GUI.

lib 1. swing-layout-1.0.jar — JAR file containing exensions to the Swinglayout manager library used by the Swing GUI.

Contains instructions for doing the following:README.txt

1. Using Caché to import and build the Caché application and thenpopulate it with sample data.

2. Configuring and building the provided NetBeans starter project andthen launching its GUI.

Complete the project by using the Java Binding or JDBC to implement the following methodsin CurrencyOrderController. These methods are invoked by the Swing GUI(ProccessCurrencyOrderUI).

1. public CurrencyOrderController() — A zero argument constructor.

2. public String[] getCityAndStateList() — Returns an array of String. The GUI uses thearray to populate City and State drop-down list. The GUI invokes the method when itloads.

3. public String[] getATMLocations(String item) — Returns an array of String. The GUIuses the array to populate the Select ATM drop-down list. The GUI invokes the methodin response to a selection on the City and State drop-down list. The GUI passes the methodthe String selected from the City and State drop-down list.

4. public String[] getCurrencies(String item) — Returns an array of String. The GUI usesthe array to populate both the Requested Currency and Supplied Currency drop-downlists. The GUI invokes the method in response to a selection from the Select ATM drop-

62                                                                                                                 Lab Book: Java Projections

Starter Files for Project One — Swing Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

down list. The GUI passes the method the String selected from the Select ATM drop-downlist.

5. public String previewCurrencyOrder(String requestedCurrency, BigDecimalsuppliedCurrencyAmount, String suppliedCurrency, String name, String email,)— Returns a String containing the fee, exchange rate, and supplied currency amount forthe prospective currency order. The GUI displays the String on its TextArea. The GUIinvokes the method when its Preview button is pushed. Here are descriptions of the valuesassigned to the method's arguments when the GUI invokes it.

DescriptionArgument Name

A String containing the text displayed in the GUI's Name textfield.

name

A String containing the text displayed in the GUI's Email textfield.

email

A String containing the text selected in the GUI's Select the

Currency You Want drop-down list.requestedCurrency

A java.math.BigDecimal object containing the data displayed inthe GUI's Amount text box.

suppliedCurrencyAmt

A String containing the text selected in the GUI's Select the

Currency You Have drop-down list.suppliedCurrency

6. public String processCurrencyOrder(String atmSerialNum, String name, Stringemail, String requestedCurrency, BigDecimal suppliedCurrencyAmt, StringsuppliedCurrency) — Creates and processes a currency order. The GUI invokes themethod when the Submit button is pressed. It returns a formatted String containing thedetails of the processed CurrencyOrder for display on the GUI's TextArea. The method

Lab Book: Java Projections                                                                                                                 63

Starter Files for Project One — Swing Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

accepts six arguments. Here are the descriptions of the values values that the GUI assignsto the arguments.

DescriptionArgument Name

A String containing the text selected in the GUI's Select an ATM

drop-down list.atmSerialNum

A String containing the text displayed in the GUI's Name textfield.

name

A String containing the text displayed in the GUI's Email textfield.

email

A String containing the text selected in the GUI's Select the

Currency You Want drop-down list.requestedCurrency

A java.math.BigDecimal object containing the data displayed inthe GUI's Amount text box.

suppliedCurrencyAmt

A String containing the text selected in the GUI's Select the

Currency You Have drop-down list.suppliedCurrency

64                                                                                                                 Lab Book: Java Projections

Starter Files for Project One — Swing Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

DStarter Files for Project One —Web Version

FCEWebProj1Starter.zip contains a set of files to help you implement a Web based solutionfor project one. The files are organized as a NetBeans 5.0 project. You can either open theproject in NetBeans or import them into your favorite IDE.

The files include a completed Web-based GUI interface for the project along with the skeletoncode for the application's data access layer (CurrencyOrderController.java). You need onlycomplete the methods in CurrencyOrderController.java to complete the application.FCEProj1WebStarter.zip archive contains the following directories and files:

Lab Book: Java Projections                                                                                                                 65

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Project One Starter Files and Directories — Web Version

FilesDirectory

FCEWebProjStarter\web 1. order.html — The HTML and JavaScript code for theWeb interface.

2. js — Directory containing the DOJO JavaScriptlibrary used by order.html.

3. META-INF — Directory containing the Web Server'scontext descriptor.

4. WEB-INF — Directory containing the deploymentdescriptor for the Web application.

FCEProj1WebStarter\src\java\data 1. CurrencyOrderController.java — Contains the skeletonmethods that you should implement.

FCEProj1WebStarter\src\java\web 1. ajaxcontroller.java — Part of the Web interface code.Handles method calls from order.html.

2. OrderBean.java — Part of the Web interface code.Used to store order information for a particular userin the Session object.

Contains instructions for doing the following:README.txt

1. Using Caché to import and build the Caché applica-tion and then populate it with sample data.

2. Configuring and building the provided NetBeansstarter project and then launching its GUI.

Complete the project by using either the Java Binding or JDBC to implement the followingmethods in CurrencyOrderController. These methods are invoked by the Web interface(ajaxcontroller).

1. public CurrencyOrderController() — A zero argument constructor.

2. public String[] getCityAndStateList() — Returns an array of String. Invoked by theGUI to populate the Select City and State drop-down list.

66                                                                                                                 Lab Book: Java Projections

Starter Files for Project One — Web Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

3. public String[] getATMLocations(String key) — Returns an array of String. Invokedby the GUI to populate the Select An ATM drop-down list. The GUI passes the method aString containing the text selected in the Select a City and State drop-down list.

4. public String[] getCurrencies(String key) — Returns an array of String. Invoked bythe GUI to populate the Select the Currency You Want and Select the Currency You Have

drop-down lists. The GUI passes the method a String containing the text selected in theSelect an ATM drop-down list.

5. public Map previewCurrencyOrder(String suppliedCurrency, StringsuppliedCurrAmt,String requestedCurrency). Returns a Map containing the followingkeys and values:

ValueKey

A java.math.BigDecimal object representing the “Requested Amount”, that is, the total amount to be returned to the customer by the FCEapplication.

requestedAmt

A java.lang.Double object representing the fee charged by the FCEapplication for the currency exchange.

fee

A java.lang.Double object representing the exchange rate to be usedby the FCE application for the currency exchange.

exchangeRate

The method is invoked by the GUI when the Preview button is clicked. The GUI passesthree String instances to the method representing: the item selected in the Select the Cur-

rency You Have drop-down list, the information in the Amount text box, and the itemselected in the Select the Currency You Want drop-down list.

6. public String processCurrencyOrder(String atmSerialNum, String name, Stringemail, String requestedCurrency, BigDecimal suppliedCurrencyAmt, StringsuppliedCurrency, Double exchangeRate) — Returns a String. Invoked by the GUI

Lab Book: Java Projections                                                                                                                 67

Starter Files for Project One — Web Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

when the Submit button is clicked. Here are descriptions of the values assigned to themethod's arguments when the GUI invokes it.

DescriptionArgument Name

A String containing the text selected in the GUI's Select an ATM

drop-down list.atmSerialNum

A String containing the text displayed in the GUI's Name textfield.

name

A String containing the text displayed in the GUI's Email textfield.

email

A String containing the text selected in the GUI's Select the

Currency You Want drop-down list.requestedCurrency

A java.math.BigDecimal object containing the data displayed inthe GUI's Amount text box.

suppliedCurrencyAmt

A String containing the text selected in the GUI's Select the

Currency You Have drop-down list.suppliedCurrency

A java.lang.Double instance representing the exchange ratefor the currency exchange.

exchangeRate

68                                                                                                                 Lab Book: Java Projections

Starter Files for Project One — Web Version

XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/