Lab Book: Java Projections

19 downloads 294 Views 731KB Size Report
Lab Book: Java Projections ... This document contains trade secret and confidential information which is the ... such programs and related documentation .
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/

Lab Book: Java Projections Version Copyright © 2005 InterSystems Corporation. All rights reserved. This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information from the following sources: Sun Microsystems, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium at www.w3c.org. The primary document development tools were special-purpose XML-processing applications built by 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 operation and maintenance of the products of InterSystems Corporation. No part of this publication is to be used for any other purpose, and this publication is not to be reproduced, copied, disclosed, transmitted, stored in a retrieval system or translated into any human or computer language, in any form, by any means, in whole or in part, without the express prior written consent of InterSystems Corporation. The copying, use and disposition of this document and the software programs described herein is prohibited except to the limited extent set forth in the standard software license agreement(s) of InterSystems Corporation covering such programs and related documentation. InterSystems Corporation makes no representations and warranties concerning such software programs other than those set forth in such standard software license agreement(s). In addition, the liability of InterSystems Corporation for any losses or damages relating to or arising out of the use of such 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 BY INTERSYSTEMS CORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTER SOFTWARE. FOR COMPLETE INFORMATION REFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARE LICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION, COPIES OF WHICH WILL BE MADE AVAILABLE UPON REQUEST. InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves the right, in its sole discretion and without notice, to make substitutions and modifications in the products and practices described 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 product names 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 Tel: +1 617 621-0700 Fax: +1 617 374-9391 Email: [email protected]

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

Table of Contents Preface ................................................................................................................................. 1 Contents of this Book ..................................................................................................... 1 How To Use this Book .................................................................................................... 2 1 The Basics ......................................................................................................................... 3 1.1 Introduction .............................................................................................................. 3 1.2 Overview: Caché Java Binding Basics .................................................................... 3 1.3 Java Binding Quick Start ......................................................................................... 4 1.4 Java Binding Components and Resources ............................................................... 6 1.5 Java Projections ........................................................................................................ 7 1.6 Runtime Architecture ............................................................................................... 7 1.7 Full and Light Binding ............................................................................................. 8 1.8 Quiz One .................................................................................................................. 8 1.9 Creating Projections ................................................................................................. 9 1.10 Projection Details: Identifiers and Data Types ..................................................... 10 1.11 Projection Details: Collections ............................................................................ 11 1.12 Projection Details: /NEWCOLLECTIONS Flag ................................................. 12 1.13 Projection Details: Queries .................................................................................. 13 1.14 Projection Details: Persistent Classes .................................................................. 14 1.15 Quiz Two .............................................................................................................. 15 1.16 Establishing a Connection: Full and Light ........................................................... 16 1.17 Opening an Existing Object ................................................................................. 17 1.18 Creating a New Object ......................................................................................... 18 1.19 Using Collections ................................................................................................ 19 1.20 Using a Relationship ............................................................................................ 20 1.21 Quiz Three ............................................................................................................ 20 1.22 Overview: Caché JDBC ...................................................................................... 22 1.23 Caché JDBC Quick Start ..................................................................................... 22 1.24 JDBC Components and Resources ...................................................................... 23 1.25 Connection Options ............................................................................................. 24 1.26 Connecting Using DriverManager ....................................................................... 24 1.27 Connecting Using CacheDatabase ....................................................................... 25 1.28 Executing a SELECT ........................................................................................... 26 1.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 ............................................................................................................. 27 1.31 Caché Custom JSP Tag Overview ........................................................................ 28 1.32 Caché Custom Tag Resources .............................................................................. 29 1.33 Installing and Executing the Samples .................................................................. 30 1.34 Some Caché Custom Tags and their Attributes .................................................... 31 1.35 The Tag ...................................................................................................... 31 1.36 Using Custom Tags .............................................................................................. 32 1.37 Quiz Five .............................................................................................................. 33 1.38 Design Considerations: Java Binding or JDBC? ................................................. 34 2 Lab Project ..................................................................................................................... 35 2.1 Project Overview .................................................................................................... 35 2.2 Project One: Currency Order through an ATM ..................................................... 35 2.3 Project Two: Credit Card and Customer Account Payments ................................. 36 3 Advanced Topics ............................................................................................................ 39 3.1 Overview ................................................................................................................ 39 3.2 Overview: Caché Java Binding Advanced Features .............................................. 39 3.3 Using a Class Query ............................................................................................... 40 3.4 Using a Dynamic Query ......................................................................................... 40 3.5 Using OpenByQuery and a Simple Condition ....................................................... 41 3.6 Using OpenByQuery and a Complex Query .......................................................... 42 3.7 Calling By Reference and Output Arguments ........................................................ 43 3.8 Using Dynamic Binding ........................................................................................ 44 3.9 Using Batch Inserts ................................................................................................ 45 3.10 Using Transactions ............................................................................................... 46 3.11 Overview: JDBC Advanced Features ................................................................... 47 3.12 Using a Connection Pool ..................................................................................... 48 3.13 Using Implicit Joins ............................................................................................. 49 3.14 JDBC Transaction API ......................................................................................... 50 3.15 Using JDBC Transactions .................................................................................... 51 3.16 Retrieving Generated Keys .................................................................................. 51 3.17 Executing a Stored Procedure .............................................................................. 52 3.18 Executing a Stored Procedure: Multiple Result Sets ........................................... 53 3.19 Scrolling in a Result Set ....................................................................................... 54 3.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 a relational access to Caché data. The Caché 5.2 JDBC driver supports all required JDBC 3.0 features.



Caché Java Binding Mechanism. Built on top of the JDBC driver, this mechanism provides a pure object interface to Caché. Using this mechanism, Caché generates pure Java classes from your Caché classes. These Java “projection” classes serve as proxies for their Caché counterparts. This mechanism requires no object-relational mapping or additional middleware.



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



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



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

Contents of this Book This 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 lab projects 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 into three sections: 1. The Basics — Provides information and examples to help you use the basic features of the Caché Java Binding, JDBC, and the custom JSP tags. After reading this section, you will have sufficient information to complete the lab projects. 2. Lab Projects — Presents several Lab Projects as sets of use case descriptions. These use cases 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/

Preface

that you built in the Foundation courses. Note that solutions and partial solutions for several of the projects are provided separately. 3. Advanced Features — Provides information and examples to help you use features of the Caché Java Binding, JDBC, and JSP tags not described in The Basics. Before completing the lab projects, you should glance at this section to find features that you might be interested in using. None of the features described in this section are necessary for completing any of the lab projects. How To Use this Book Your goal should be to complete at least one of the Lab Projects. You are also strongly encouraged 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 for at 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 Considerations sections of Part I. 4. Skim through Part III: Advanced Features and select any that you would like to use in your 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 can build a Java Web service client for a Caché Web service using standard Java Web Service libraries and techniques. For information on building Java Web service clients see Sun Microsystem's J2EE Tu t o r i a l at http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html.

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

1 The Basics 1.1 Introduction This section presents information and examples to help you use the basic features of the Caché Java Binding, JDBC, and custom JSP tags. After completing this section, you will have 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 the material. The Appendix contains the answers to the quiz questions. The section is divided into 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 a Java application with Caché.

1.2 Overview: Caché Java Binding Basics The Caché Java Binding provides an object interface that allows Java applications to directly access Caché objects, both persistent and transient, on the Caché server. The Java Binding requires no additional middleware or object-relational mappings. The Caché Java Binding provides complete support for object database persistence including concurrency and transLab Book: Java Projections                                                                                                                   3 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

action control. In addition, the mechanism provides a sophisticated caching scheme to help minimize 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 existing Caché object. The section then presents information on the components and architecture of the Caché Java Binding and finally covers topic 1—3. The Advanced Features section covers topics 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 be on 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Java Binding Quick Start import com.intersys.objects.*;

Create a connection to Caché: Database db = CacheDatabase.GetDatabase("jdbc:Cache://localhost:1972/", , );

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 CloseObject method of CacheDatabase. Each object supports a _close method, however this method is 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

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 communication between Java clients and a Caché database server. It communicates using TCP/IP and 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 \dev\java\lib\JDK14.

Use

this

if

you

are

using

Java

1.4.x. Another

version

is

located

in

\dev\java\lib\JDK15. Use this version if you are using Java 1.5.x. Note that

when using JALAPEÑO you must use Java 1.5.x. The archives contain several packages of Java classes that provide the connection and caching mechanisms for communication with the Caché server, JDBC connectivity, and reflection support. CacheDB.jar must be on 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 class is compiled. You can also generate Java Projections using Caché Terminal without defining a Projection.

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

“JavaDoc” style class documentation for the packages in CacheDB.jar. This documentation is in \Dev\java\doc.



A set of sample Java programs that demonstrate the use of the Java Binding to connect to Caché, open existing objects, create new objects, save object changes to Caché and execute queries against Caché. These sample programs are in \dev\java\samples.



Caché documentation: See Using Java with Caché within the Caché Language Bindings section of the Caché documentation.



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

Note:

In a standard Windows installation, is C:\CacheSys. In a standard Unix or Linux installation, is /usr/cachesys.

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

Java Projections

1.5 Java Projections From the perspective of a Java application, Java Projections form the heart of the Java Binding mechanism. A Java projection of a Caché class is a pure Java class that serves as a proxy for a Caché class within the Java application. A Java projection of a Caché class provides a communication link between the Java application and the Caché class. The Java application uses the projection like any other Java class: creating instances, calling methods, getting and setting property values and so on. The projection, in turn, invokes the corresponding methods on 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

Note:

The Java Binding caches the values of object properties on the client-side. So, when the Java application invokes a “Get” method for a property, there is no call to the server. 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 between them. Full and Light Binding Comparison Binding Type

Capabilities

Light Binding

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

Full Binding

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

1.8 Quiz One Question 1: Which one of the following must be on your Java application's class path when using the Caché Java Binding? 1. \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 and Light Java Binding?

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

Creating Projections

1. The Light Binding requires that an application use fewer Java projections of Caché classes than the Full Binding. 2. The Light Binding supports only a relational interface to the database whereas the Full Binding supports both a relational and an object interface. 3. The Light Binding uses only projections of transient classes whereas the Full Binding uses 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 Full Binding. 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 to Caché data. 3. A Java class automatically generated by Caché that contains SQL queries for accessing Caché 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 a projection 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

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 Data Types The names of Caché class elements correspond fairly closely to the names of their Java projections. The following table describes some of the potential differences: Mappings: Caché Identifiers to Java Identifiers Caché Class

Java Projection

Package Names

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

Property Names

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

Class and Method Names

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

Variable Names

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

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

Projection Details: Collections

The Caché Java Class Generator projects Caché data types to Java data types according to the CLIENTDATATYPE attribute of the Caché data type class. The following table describes several of the mappings: Mappings: Caché Datatypes to Java Datatypes Caché Data Type

CLIENTDATATYPE

Java Data Type

%String

VARCHAR

java.lang.String

%Name

VARCHAR

java.lang.String

%Integer

INTEGER

java.lang.Integer

%Float

DOUBLE

java.lang.Double

%Date

DATE

java.sql.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é Collection types:

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

The Basics

Mappings: Caché Collections to Java Collections Collection Type

Projection Type

Arrays

java.util.Map



%Library.ArrayOfDataTypes



%Library.ArrayOfObjects

Lists

java.util.List



%Library.ListOfDataTypes



%Library.ListOfObjects

%Library.RelationshipObject

com.intersys.classes.RelationshipObject

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

1.12 Projection Details: /NEWCOLLECTIONS Flag Caché 5.2 provides the /NEWCOLLECTIONS flag to control the projection of collection properties. When /NEWCOLLECTIONS is set to 1, the default value in Caché 5.2, collection properties project to Java using the above mapping. You can set the flag either when defining a 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Projection Details: Queries

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

Projection Type (/NEWCOLLECTIONS=0). All types are deprecated.

Arrays



com.intersys.classes.ArrayOfDataTypes



%Library.ArrayOfDataTypes



com.intersys.classes.ArrayOfObjects



%Library.ArrayOfObjects

Both types implement java.util.Map. Use this interface with objects of these types.

Lists



com.intersys.classes.ListOfDataTypes



%Library.ListOfDataTypes



com.intersys.classes.ListOfObject



%Library.ListOfObjects

Both types implement java.util.List. Use this interface with objects of these types.

Note that the /NEWCOLLECTIONS flag applies only to collection properties. It does not apply to method return types. The projected return type of a Caché method that returns a collection is 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 as dynamic queries.

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

The Basics

Caché Query Types Caché Query Type

Java Client Access

Class Queries

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 a method, named query_, that returns an initialized CacheQuery object. Alternatively, the Java client can create a new CacheQuery object using a constructor and initialize it using the name of the class query.

Dynamic SQL

Use the com.intersys.objects.Database openByQuery method. Pass the SQL string to the method. The method returns a java.util.Iterator object containing a set of opened objects. Note that the SQL string must meet certain requirements. See the Java documentation for details. Alternatively, initialize a com.intersys.objects.CacheQuery object with the SQL string. Use execute to execute the query. The method returns a standard java.sql.ResultSet object.

1.14 Projection Details: Persistent Classes Persistent Caché classes have the ability to store themselves to the database. Java Projections of 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 opens the 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 persistent Caché objects. Note that all of the methods throw checked exceptions of type CacheException.

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

Quiz Two

Persistent Object Methods Method

Description

_open

Opens the object with the specified id. Returns a instance of RegisteredObject that can be cast to the correct type. Arguments include: •

db



id



concurrency — optional.

save

Saves the object to the database.

_deleteId

Deletes the object with the specified object ID from the database. Arguments include:

_existsId



db



id



concurrency — optional.

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

db



id

1.15 Quiz Two Question 1: Which one of the following Caché ObjectScript commands creates a Java Projection 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

Question 2: A Caché property of type %Integer projects by default to which of the following Java 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 the following 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 connection to 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/"; String username=; String password=;

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

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

Opening an Existing Object 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 Sample.Address Id

person = null; addr = null; 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics 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 type CacheException. For the sake of clarity, these code excerpts and the following do not 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 saving the 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 CloseObject method of CacheDatabase. Each object supports a _close method, however this method is deprecated and should not be used. db.closeObject(person.getOref()); person = null; db.close();

Close the database connection.

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

Using Collections 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

1.20 Using a Relationship Here are the steps for manipulating a Caché Relationship collection. In the example, there is a one-to-many relationship between Company and Employee. In addition, Employee is a subclass 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 reference to 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 that RelationshipObject supports the asList method that returns a java.util.List representation of 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 a com.intersys.objects.Database object? Assume that url, username, and password are variables of type java.lang.String.

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

Quiz Three

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 persistent object on the Caché Server and its corresponding Java proxy object? Assume that db refers to an appropriately initialized Database object and that id refers to the object ID of an existing 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é classes Sample.Contact and Sample.PhoneNumber and that the PhoneNumbers property represents the collection of Sample.PhoneNumber objects within Sample.Contact. Assume also that contact 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

1.22 Overview: Caché JDBC Caché 5.2 provides a high-performance Level 4 JDBC database driver. It is pure Java and involves no Caché-specific binary code and no JDBC-ODBC bridge. The driver supports the JDBC 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 executing a dynamic SQL SELECT statement. The section then describes general information about the Caché JDBC driver and then covers topics 1–2. The Advanced Features section covers topics 4–7.

1.23 Caché JDBC Quick Start Here are the basic steps for connecting a Java application to Caché using the Caché JDBC driver and executing an SQL SELECT command: 1. Ensure

that

CacheDB.jar is \Dev\java\Lib\JDK14.

on

your

class

path.

The

file

is

in

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/"; String user = ; String password = ";

Load the Caché JDBC driver and create the connection:

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

JDBC Components and Resources 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 classname. java.sql.ResultSet rs = stmt.executeQuery(stQuery);

Retrieve the query results: int colnum = rsmd.getColumnCount(); while (rs.next()) { for (int i=1; i

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 element immediately after the existing elements and before the closing 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 \webapps. Shutdown Tomcat. Create \webapps\cache. Copy all of the .jsp files and the WEB-INF directory and its contents from \Dev\Java\Samples\JSP to the new directory. 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. See Caché Custom Tag Resources in this document for instructions.

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

Some Caché Custom Tags and their Attributes

1.34 Some Caché Custom Tags and their Attributes The following table describes some of the Caché custom JSP tags and their attributes. Some Custom Tags Tag

Description



Creates a connection to Caché.



Closes the connection to Caché.



Displays the contents of an object. Optionally, allows updating the content.



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



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

1.35 The Tag The tag creates an HTML SELECT list (drop-down or multi-value) using the values of a field of the specified table (class). When the HTML form containing the SELECT element is submitted, a query that uses the selected data as a parameter is executed. Here are the database related atttributes of the tag: •

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



property — The property whose values populate the list. If the property is an object property, then the value attribute of the generated tags will have object IDs as 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 tag: Lab Book: Java Projections                                                                                                                 31 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics



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



name — The value becomes the value of the name attribute of the generated HTML SELECT 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 the list. When the element is selected, submitting the form generates no query.

The tag uses a query of the following form to populate the HTML Select element that it generates: SELECT DISTINCT FROM ORDER BY

1.36 Using Custom Tags The following JSP page, listNames.jsp, uses the tag to connect to Caché and then the tag to display the Name field for each row of the Sample.Employee table: Table Content


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

Quiz Five

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. \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 tag library 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

The Basics

1.38 Design Considerations: Java Binding or JDBC? You have the choice of connecting your Java application to Caché using either the Java Binding mechanism or standard relational JDBC. You can of course use both modes in a single 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 and updating database information. The light Java Binding, however, nearly matches the efficiency of JDBC. 2. Development (maintenance) Efficiency: The Java Binding mechanism allows an application 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 the data provided by the JDBC result set and the object-oriented representation required by the application. Removing this difficult and error prone translation step can greatly increase development and maintenance efficiency. You should also remember that the light Java binding provides an excellent compromise. It provides 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 binding cannot execute Caché instance methods that return objects.

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

2 Lab Project 2.1 Project Overview This section presents a series of lab projects that involve connecting Java applications to the Caché 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, one project simulates an ATM that a customer can use to perform a currency exchange with the FCE system. Your task is to design and build the Java application and connect it to FCE using the Java Binding, JDBC, or a combination of the two. In addition to the project descriptions, we have provided the following resources to help you complete the projects: •

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



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

2.2 Project One: Currency Order through an ATM The first project is to create a Java application (either Swing or Web-based) that simulates a cash 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/

Lab Project

customers to perform a cash exchange using one of the system's ATMs. Here is the process that 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 currency the 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 that would be returned to the user in the prospective transaction. Note for Project One the payments are cash only. Credit card and customer account payments for currency exchanges are not supported. 6. The user submits the currency order. The selected ATM determines whether or not it can process 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. The application notifies the customer that the currency order was rejected. Project One does not involve credit card or customer account payments. Users do not need to 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 you choose.

2.3 Project Two: Credit Card and Customer Account 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Project Two: Credit Card and Customer Account Payments

1. Users can pay for their cash exchanges using credit cards. The users enters the card type and number. This information is recorded by the system when it process the currency order. 2. Users can pay for cash exchanges using their accounts with the system. The user enters name 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 the supplied currency type for the cash exchange.



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

Lab Book: Java Projections                                                                                                                 37 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/

3 Advanced Topics 3.1 Overview This section presents additional features of both the Caché Java Binding and JDBC support that are not covered in The Basics.

3.2 Overview: Caché Java Binding Advanced Features 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/

Advanced Topics

3.3 Using a Class Query Here are the steps for using the com.intersys.objects.CacheQuery class to execute a class query. The Sample.Person class contains the ByName query. This query accepts a single string representing a name as a parameter. The query retrieves the object id, Name, DOB, and SSN 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. Note that the com.intersys.classes package contains a ResultSet class as well. Use the fully qualified 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 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Using OpenByQuery and a Simple Condition

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. The method returns a java.sql.ResultSet object. Note that the com.intersys.classes package contains a ResultSet class as well. Use the fully qualified name: java.sql.ResultSet, to prevent 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 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 particular type that satisfy a condition. Specify the condition using SQL syntax. The condition must be 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Advanced Topics



"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 parameters for 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 the parameter array. Note that the method returns a java.util.Iterator for the collection of opened 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 the following conditions: •

The first returned column must be the fully qualified %ID column for the table. For example, when opening Sample.Person objects, the first column must be “Sample.Person.%ID” .



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

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

Calling By Reference and Output Arguments

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 output parameters 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. The values that they hold cannot be changed. Java projections wrap arguments that are passed by reference or that are output parameters in special Holder classes. The server can update the values contained within these Holder classes and thereby simulate output parameters and passing arguments by reference. Here is an example of a Caché method, named AddOne, that accepts a single %Integer as an argument. The argument can be passed by reference to the method. Lab Book: Java Projections                                                                                                                 43 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Advanced Topics 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 documentation for the Caché Java Binding.

3.8 Using Dynamic Binding You can use the classes of the com.intersys.objects.reflect package to bind dynamically to Caché objects. The following code sample includes a method, showObject, that outputs the values 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Using Batch Inserts 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 and displays the name of each along with its value. If the field value is itself an object, instance of 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 and LightDynamicBindingSample.java provide more in depth examples of dynamic binding including dynamic binding with the Light Java Binding. These programs are in \Dev\java\samples.

3.9 Using Batch Inserts Java Projections provide methods for performing batch inserts. Note that the connection object used with batch insert methods is a java.sql.Connection object. Create this connection using 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. The method returns an instance of Object representing the batch to which the data has been Lab Book: Java Projections                                                                                                                 45 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Advanced Topics

added. The first argument represents the “batch” . If the argument is null the method creates a new batch. Note that Name and SSN are required fields for Sample.Person so values 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 line as 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 list containing 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 random SSN with the correct format "3N1""-""2N1""-""4N". See the sample program CJTest2.java in \Dev\java\samples.

3.10 Using Transactions The com.intersys.objects.Database interface provides the following methods for transaction support: Method

Description

transactionStart

Starts a transaction

transactionCommit

Commits a transaction

transactionRollback

Rolls back a transaction

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

Overview: JDBC Advanced Features

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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Advanced Topics

3.12 Using a Connection Pool The

com.intersys.jdbc.CacheConnectionPoolDataSource class implements the javax.sql.ConnectionPoolDataSource interface providing a connection pool for your Java client

applications. 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 + "/; String user = ; String password = ;

3. Instantiate CacheConnectionPoolDataSource object. Use the reStart method to close all of the physical connections and empty the pool. Use setURL to set the database url for the 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 XML to PDF by RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Using Implicit Joins

3.13 Using Implicit Joins Caché SQL supports an Implicit Join syntax, represented by the –> operator, that simplifies the SQL for certain types of joins. Use the –> operator whenever a table has a reference column, that is, a column a containing the ID values of another table. In a Caché parent-child relationship the table containing the child objects has a column that references the parent table. The following query returns the names of all employees whose name begins with “A” and works 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 any other 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