10.07.2015 Views

JDBC Developer's Guide - Supra - Cincom

JDBC Developer's Guide - Supra - Cincom

JDBC Developer's Guide - Supra - Cincom

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

SQL ACCESS FOR SUPRASERVER PDM ®<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>P25-9504-03


Release information for this manualSQL Access for SUPRA Server PDM ® <strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03, isdated September 1, 2011. This document supports Release 2.0 of SQL Accessfor SUPRA Server PDM.<strong>Cincom</strong> Technical Support for SQL Access for SUPRA Server PDMAll customers Web: http://supportweb.cincom.comU.S.A customers Phone: 1-800-727-3525Fax: (513) 612-2000Attn: SQL Access for SUPRA Server PDMSupportMail: <strong>Cincom</strong> Systems, Inc.Attn: SQL Access for SUPRA Server PDMSupport55 Merchant StreetCincinnati, OH 45246-3732USAOutside of U.S.A. All: Visit the support links athttp://www.cincom.com to find contactinformation for your nearest CustomerService Center.Using this manual%ORDB% refers to the directory identified by the ORDB environment variable.This will be set to the installation directory.This document may use both UNIX ($ORDB/..) and Windows (%ORDB%\..)notations. Please adjust the environment variable and slashes accordingly foryour platform.


Contents1. Overview ................................................................................ 7Introduction ................................................................................................ 7What is <strong>JDBC</strong>? .............................................................................................. 8Basic driver architecture ................................................................................. 9<strong>Cincom</strong> ORDB extensions to the <strong>JDBC</strong> standard .................................................... 10Supported JDK and <strong>JDBC</strong> versions .................................................................... 112. Verifying a <strong>JDBC</strong> Driver installation ............................................. 12Introduction .............................................................................................. 12Checking installed directories and files ............................................................. 13Directories for <strong>JDBC</strong> ............................................................................... 13Check the environment variables ..................................................................... 14Determining the version of the <strong>JDBC</strong> Driver ................................................... 14Testing <strong>JDBC</strong> and the database connection .................................................... 15Running the jdbcHelloWorld.java program..................................................... 153. Basic Features ........................................................................ 19Introduction .............................................................................................. 19First steps in <strong>JDBC</strong> ...................................................................................... 20Step 1: Register the <strong>JDBC</strong> Driver ................................................................ 20Step 2: Open a connection to a database ..................................................... 21Step 3: Create a Statement object ............................................................. 21Step 4: Execute a query and return a ResultSet object ..................................... 22Step 5: Process the ResultSet object ........................................................... 23Step 6: Close the ResultSet and Statement Objects ......................................... 23Step 7: Close the Connection .................................................................... 23Sample: Connecting, querying, and processing the results ....................................... 24Datatype mappings ...................................................................................... 25<strong>Cincom</strong> ORDB <strong>JDBC</strong> extension types ............................................................. 26Error Messages and <strong>JDBC</strong> ............................................................................... 27<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 4Contents


4. <strong>Cincom</strong> ORDB Extensions ........................................................... 28Introduction .............................................................................................. 28Classes of the ordbjava.jdbc package ............................................................... 28Class ordbDriver .................................................................................... 29Class ordbObject ................................................................................... 29Class ordbGlo ....................................................................................... 30Class ordbCollection ............................................................................... 30Working with <strong>Cincom</strong> ORDB objects and object references ...................................... 31Accessing attribute values ........................................................................ 31Inserting, deleting, and updating database instances ........................................ 33Invoking database methods ....................................................................... 36Creating custom Java classes for <strong>Cincom</strong> ORDB objects .......................................... 38Generating Java classes from a database schema ............................................ 39Generating Java classes with the CustomMappingDlg class ................................. 39Annotated examples of custom mapped classes .............................................. 40Relating Java classes to database class names ................................................ 48Controlling when custom mapping occurs ...................................................... 50Inserting, deleting, and updating with custom mapping ..................................... 55Writing your own custom mapping classes ..................................................... 58Working with <strong>Cincom</strong> ORDB collections .............................................................. 61Retrieving a collection and its elements ....................................................... 62Working with heterogeneous collections ....................................................... 65Homogeneous collections and Java primitive arrays ......................................... 67Creating and modifying collections .............................................................. 69Collections and custom mapping................................................................. 73Freeing <strong>Cincom</strong> ORDB workspace storage used by ordbCollections ........................ 755. <strong>Cincom</strong> ORDB <strong>JDBC</strong> Notes .......................................................... 76Introduction .............................................................................................. 76Supported <strong>JDBC</strong> 3.0 interfaces ........................................................................ 77Array .................................................................................................. 77Blob ................................................................................................... 77Clob ................................................................................................... 77Connection .......................................................................................... 78DatabaseMetaData ................................................................................. 79Driver ................................................................................................. 79PreparedStatement ................................................................................ 80Ref .................................................................................................... 80ResultSet ............................................................................................. 81ResultSetMetaData ................................................................................. 83SQLInput ............................................................................................. 83SQLOutput ........................................................................................... 84Statement ........................................................................................... 84Struct ................................................................................................. 84<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 5Contents


6. Coding tips and troubleshooting .................................................. 85Introduction .............................................................................................. 85<strong>JDBC</strong> and multi-threading .............................................................................. 86Performance optimization ............................................................................. 87Disabling auto-commit mode ..................................................................... 87Using the array interface ......................................................................... 88Automatic custom mapping ....................................................................... 89Connection pooling ................................................................................. 89Trapping exceptions ............................................................................... 90Schema locks ........................................................................................ 91Logging <strong>JDBC</strong> calls ...................................................................................... 92A. <strong>JDBC</strong> Samples ......................................................................... 93Prerequisites ............................................................................................. 93Accessing <strong>JDBC</strong> samples ................................................................................ 94Sample programs ........................................................................................ 95Index ....................................................................................... 96<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 6Contents


1. OverviewIntroductionThis chapter provides an overview of the <strong>Cincom</strong> Object Relational Database(ORDB) implementation of <strong>JDBC</strong> and contains these topics:♦♦♦♦What is <strong>JDBC</strong>?Basic driver architecture<strong>Cincom</strong> ORDB extensions to the <strong>JDBC</strong> standardSupported JDK and <strong>JDBC</strong> versions<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 7Chapter: 1. OverviewSection: Introduction


What is <strong>JDBC</strong>?<strong>JDBC</strong> (Java Database Connectivity) is a standard Java interface for connectingto relational databases from Java. The <strong>JDBC</strong> standard was defined by SunMicrosystems, allowing individual providers to implement and extend thestandard with their own <strong>JDBC</strong> drivers.Based on the X/Open SQL Call Level Interface, <strong>JDBC</strong> complies with the SQL92Entry Level standard.In addition to the standard <strong>JDBC</strong> API, the <strong>Cincom</strong> ORDB driver has extensions toallow access to special features and functions provided by the <strong>Cincom</strong> ObjectRelational Database. For more information on these extensions, see "4. <strong>Cincom</strong>ORDB Extensions" on page 28.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 8Chapter: 1. OverviewSection: What is <strong>JDBC</strong>?


Basic driver architectureThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver is a Type II driver that is targeted toclient-server Java applications programmers and Java-based middle-tierdevelopers.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver is written in a combination of Java and Cbecause it must make calls to the <strong>Cincom</strong> ORDB C API libraries. The driverrequires the presence of the <strong>Cincom</strong> ORDB Client Runtime libraries and othernecessary files on each client machine or middle-tier application server onwhich it is installed.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 9Chapter: 1. OverviewSection: Basic driver architecture


<strong>Cincom</strong> ORDB extensions to the <strong>JDBC</strong> standardThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver supports many extensions that provide access tospecial features and functions of the <strong>Cincom</strong> ORDB database. For moreinformation on these extensions, see "4. <strong>Cincom</strong> ORDB Extensions" on page 28.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 10Chapter: 1. OverviewSection: <strong>Cincom</strong> ORDB extensions to the <strong>JDBC</strong> standard


2. Verifying a <strong>JDBC</strong> DriverinstallationIntroductionThis chapter guides you through the basics of testing your installation andconfiguration, and running a simple application. It assumes that you havealready installed the <strong>Cincom</strong> ORDB client runtime, which includes the <strong>JDBC</strong>driver. This chapter also discusses:♦ Checking installed directories and files♦ Checking the environment variables♦ Compiling and running Java♦ Testing <strong>JDBC</strong> and the database connection<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 12Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Introduction


Checking installed directories and filesThis section assumes that you have already installed the Sun Microsystems JavaDeveloper’s Kit (JDK) on your system. The <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver iscompatible with JDK version 1.4.2.Directories for <strong>JDBC</strong>The <strong>Cincom</strong> ORDB client runtime includes the file %ORDB%\ordbjava.jar. Theordbjava.jar file contains the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver implementationclasses.In addition to the jar file, <strong>Cincom</strong> ORDB development kit installations will alsohave the following:♦ %ORDB%\demo\jdbc\samples directory with several sample files♦ Command line mapping tool in file:- On Windows: %ORDB%\ddltojava.exe- On Unix: $ORDB/utilities/ddltojava%ORDB% refers to the directory identified by the ORDB environment variable.This will be set to the installation directory.This document will use both UNIX ($ORDB/..) and Windows (%ORDB%\..)notations. Please adjust the environment variable and slashes accordingly foryour platform.The javadoc tool was used to generate reference information about the javaclasses that are contained in the ordbjava.jar file. For detailed information onthe java classes, refer to the reference files located in your%ORDB%/docs/jdbc/ordbjava directory.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 13Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Checking installed directories and files


Check the environment variablesIn addition to the standard <strong>Cincom</strong> ORDB client environment variables, youmust set the CLASSPATH to include your installed <strong>JDBC</strong> driver:%ORDB%/ordbjava.jarDetermining the version of the <strong>JDBC</strong> DriverIf at any time you need to determine the version of the <strong>JDBC</strong> driver that youinstalled, you can invoke the getDriverVersion() method of the <strong>JDBC</strong>DatabaseMetaData interface:// This example displays the version information about the <strong>Cincom</strong>ORDB <strong>JDBC</strong> Driverpackage demo.jdbc.samples;import java.lang.*;import java.sql.*;{class driverVersion {public static void main (String args []) throws SQLException// Load the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driverDriverManager.registerDriver(new ordbjava.jdbc.ordbDriver());// connect to demodb as public userConnection conn =DriverManager.getConnection("jdbc:cincomordb:demodb","public",null);// Create <strong>Cincom</strong> ORDB DatabaseMetaData objectDatabaseMetaData meta = conn.getMetaData ();// gets driver info:System.out.println("<strong>Cincom</strong> ORDB <strong>JDBC</strong> driver version is " +meta.getDriverVersion());}conn.close();}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 14Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Check the environment variables


Testing <strong>JDBC</strong> and the database connectionThe %ORDB%\demo\jdbc\samples directory contains sample programs for the<strong>Cincom</strong> ORDB <strong>JDBC</strong> driver. The jdbcHelloWorld.java program is designedto test <strong>JDBC</strong> and the database connection. The program queries you for thefollowing information:♦♦User namePassword♦ Name of a database to which you want to connectFor a complete list of the sample program names, see "Sample programs" onpage 95.The sample code in the %ORDB%\demo\jdbc\samples directory belongsto the demo.jdbc.samples package.Running the jdbcHelloWorld.java program1. Access a running database.2. Open the %ORDB%\demo\jdbc\samples\ directory, and compile and run thejdbcHelloWorld.java program.- Sample compilation command from the command prompt (Windows NTwith SUN’s JDK):javac –classpath %ORDB%\demo\jdbc\samples\jdbcHelloWorld.java- Sample run command from the command prompt:java –cp %ORDB%\ordbjava.jar;%ORDB%demo.jdbc.samples.jdbcHelloWorldIf the results of the query print without error, then your Java and <strong>JDBC</strong>installations are correct.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 15Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Check the environment variables


Functions of the jdbcHelloWorld.java programAlthough jdbcHelloWorld.java is a simple program, it illustrates severalimportant functions:♦♦♦♦Imports the necessary Java classes, including <strong>JDBC</strong> classesRegisters the <strong>JDBC</strong> driverConnects to the databaseExecutes a simple query♦ Outputs the query results to your screenFor detailed information on these functions, see "First steps in <strong>JDBC</strong>" onpage 20.Example of the jdbcHelloWorld.java programThe following is a listing of jdbcHelloWorld.java for the <strong>JDBC</strong> driver://// This example demonstrates a simple <strong>JDBC</strong> application.//// This sample can be used to check the <strong>JDBC</strong> installation.// Run the application and provide connection information for// a demo/jdbc/samples/ Database that you have access to. It will select// and display "Hello World" from the database.//import java.io.*;//// You need to import java.sql package to use <strong>JDBC</strong>//import java.sql.*;class jdbcHelloWorld {public static void main (String args []) throws SQLException, IOException{// Load the <strong>JDBC</strong> driverDriverManager.registerDriver(new ordbjava.jdbc.ordbDriver());// Prompt the user for connect information<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 16Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Check the environment variables


System.out.println ("Please enter information to test connection to thedatabase");String user;String password;String database;user = readEntry ("user: ");int slash_index = user.indexOf ('/');if (slash_index != -1) {password = user.substring (slash_index + 1);user = user.substring (0, slash_index);}elsepassword = readEntry ("password: ");database = readEntry ("database name: ");System.out.print ("Connecting to the database...");System.out.flush ();System.out.println ("Connecting...");Connection conn =DriverManager.getConnection("jdbc:cincomordb:" + database,user, password);System.out.println ("connected.");// Create a statementStatement stmt = conn.createStatement ();// Do the SQL "Hello World" thingResultSet rset = stmt.executeQuery ("select 'Hello World' from classdb_user");// Display Resultswhile (rset.next ())System.out.println (rset.getString (1));// close the result set, the statement and connectionrset.close();stmt.close();<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 17Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Check the environment variables


conn.close();System.out.println ("Your <strong>Cincom</strong> ORDB <strong>JDBC</strong> installation is correct.");}// Utility function to read a line from standard inputstatic String readEntry (String prompt) {try {StringBuffer buffer = new StringBuffer ();System.out.print (prompt);System.out.flush ();int c = System.in.read ();while (c != '\n' && c != -1) {buffer.append ((char)c);c = System.in.read ();}return buffer.toString ().trim ();} catch (IOException e) {return "";}}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 18Chapter: 2. Verifying a <strong>JDBC</strong> Driver installationSection: Check the environment variables


3. Basic FeaturesIntroductionThis chapter covers the basic steps taken in any <strong>JDBC</strong> application. It alsodescribes additional Java and <strong>JDBC</strong> features supported by the <strong>Cincom</strong> ORDB<strong>JDBC</strong> driver, including the following topics:♦ How to get up and running with the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver♦♦♦Example of connecting, querying, and processing the resultsDatatype mappingsError messages and <strong>JDBC</strong><strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 19Chapter: 3. Basic FeaturesSection: Introduction


First steps in <strong>JDBC</strong>When using the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver, you must include certain driverspecificinformation in your programs.In the form of a tutorial, the following steps describe where and how to addthe information. It will also guide you through creating code for connecting toand querying a database from the client.To connect to and query a database from the client, you must provide code forthese tasks:♦ Registering the <strong>JDBC</strong> Driver♦♦♦♦♦♦Opening a connection to a databaseCreating a Statement objectExecuting a query and returning a ResultSet objectProcessing the ResultSetClosing the ResultSet and Statement objectsClosing the connectionYou must supply <strong>Cincom</strong> ORDB driver-specific information for the first twotasks, which allow your program to use the <strong>JDBC</strong> API to access a database. Forthe other tasks, you can use standard <strong>JDBC</strong> Java code as you would for anyJava application.Step 1: Register the <strong>JDBC</strong> DriverYou must provide the code to register your installed driver with your program.You do this with the static registerDriver() method of the <strong>JDBC</strong>DriverManager class. This class provides a basic service for managing a setof <strong>JDBC</strong> drivers.You register the driver only once in your Java application:DriverManager.registerDriver (new ordbjava.jdbc.ordbDriver());Alternatively, you can use the forName( ) method for the java.lang.Class classto load the <strong>JDBC</strong> drivers directly. For example:Class.forName ("ordbjava.jdbc.ordbDriver");<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 20Chapter: 3. Basic FeaturesSection: First steps in <strong>JDBC</strong>


Step 2: Open a connection to a databaseYou open a connection to the database with the static getConnection()method of the <strong>JDBC</strong> DriverManager class. This method returns an object ofthe <strong>JDBC</strong> Connection class which needs as input a userid, password, connectstring that identifies the <strong>JDBC</strong> driver to use, and the name of the database towhich you want to connect.Connecting to a database is a step where you must enter <strong>Cincom</strong> ORDB <strong>JDBC</strong>driver-specific information in the getConnection() method.Understanding the forms of getConnection()♦♦Specifying a database URL, user id, and password:DriverManager.getConnection(String URL, String user, Stringpassword);where the URL is in the form of:jdbc:cincomordb:The following example connects user foo with password bar to a databasenamed testdb:Connection conn = DriverManager.getConnection("jdbc:cincomordb:testdb", "foo", "bar");Specifying a database URL and Properties objectDriverManager.getConnection(String URL, Properties info);where the URL is in the form of:jdbc:cincomordb:In addition to the URL, use an object of the standard Java Propertiesclass as input. For example:java.util.Properties info = new java.util.Properties();info.put ("user", "foo");info.put ("password","bar");Connection conn =DriverManager.getConnection("jdbc:cincomordb:testdb",info);Step 3: Create a Statement objectOnce you connect to the database by creating your Connection object, thenext step is to create a Statement object. The createStatement()method of your <strong>JDBC</strong> Connection object returns an object of the <strong>JDBC</strong>Statement class. Continuing the example from the previous section where wecreated the Connection object conn, now we will create the Statementobject:Statement stmt = conn.createStatement();<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 21Chapter: 3. Basic FeaturesSection: First steps in <strong>JDBC</strong>


Step 4: Execute a query and return a ResultSet objectTo query the database, use the executeQuery() method of your Statementobject. This method takes an SQL statement as input and returns an object ofthe <strong>JDBC</strong> ResultSet class.To continue the example, once you create the Statement object stmt, thenext step is to execute a query. The following example populates aResultSet object with the contents of the name column of a database classnamed resort:ResultSet rset = stmt.executeQuery ("SELECT name FROM resort");<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 22Chapter: 3. Basic FeaturesSection: First steps in <strong>JDBC</strong>


Step 5: Process the ResultSet objectOnce you execute your query, use the next() method of your ResultSetobject to iterate through the results. This method loops through the result setrow by row, detecting the end of the result set when it is reached.To pull data out of the result set as you iterate through it, use the variousgetXXX() methods of the ResultSet object, where XXX corresponds to aJava datatype.For example, the following code will iterate through the ResultSet objectrset from the previous section, and will retrieve and print each resort name:while (rset.next())System.out.println (rset.getString(1));The next() method returns false when it reaches the end of the result set.The resort names are materialized as Java Strings.Step 6: Close the ResultSet and Statement ObjectsYou should explicitly close the ResultSet and Statement objects after youfinish using them. This applies to all ResultSet and Statement objects youcreate when using the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver. Although the driver hasfinalize methods that will perform the cleanup, applications should explicitlyclose ResultSet and Statement objects in order to release resources assoon as possible.For example, if your ResultSet object is rset and your Statement objectis stmt, close the result set and statement with these lines:rset.close()stmt.close();When you close a Statement object that a given Connection objectcreates, the connection itself remains open.Step 7: Close the ConnectionYou must close your connection to the database once you finish your work. Usethe close() method of the Connection class to do this. For example, ifyour Connection object is conn, close the connection with this statement:conn.close();<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 23Chapter: 3. Basic FeaturesSection: First steps in <strong>JDBC</strong>


Datatype mappingsThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver supports the SQL datatypes required by <strong>JDBC</strong>1.22.For reference, the following table shows the default mappings between <strong>JDBC</strong>datatypes, native Java datatypes, and SQL datatypes:♦♦♦The Standard <strong>JDBC</strong> Datatypes column lists the datatypes supported by the<strong>JDBC</strong> 1.22 standard. The java.sql.Types class defines all of thesedatatypes.The Java Native Datatypes column lists the datatypes defined by the Javalanguage.The SQL Datatypes column lists the SQL datatypes that exist in thedatabase.Standard <strong>JDBC</strong> datatypes Java native datatypes SQL datatypesjava.sql.Types.CHAR java.lang.String CHAR(n)java.sql.Types.VARCHAR java.lang.String VARCHAR(n), STRINGjava.sql.Types.BINARY byte[] BIT(n) (n < 33)java.sql.Types.BIT Boolean BIT(1)java.sql.Types.VARBINARY byte[] BIT VARYING(n)java.sql.Types.NUMERIC java.math.BigDecimal NUMBER(p,s)java.sql.Types.DECIMAL java.math.BigDecimal DECIMAL(p,s)java.sql.Types.INTEGER int INTEGERjava.sql.Types.SMALLINT short SMALLINTjava.sql.Types.FLOAT float FLOAT(p)java.sql.Types.REAL double REALjava.sql.Types.DOUBLE double DOUBLE PRECISIONjava.sql.Types.DATE java.sql.Data DATEjava.sql.Types.TIME java.sq.Time TIMEjava.sql.Types.TIMESTAMP java.sql.Timestamp LONGRAWjava.sql.Types.ARRAY java.sql.Array SETjava.sql.Types.ARRAY java.sql.Array MULTISETjava.sql.Types.ARRAY java.sql.Array SEQUENCEjava.sql.Types.REF jav.sql.Ref OBJECT REFERENCE<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 25Chapter: 3. Basic FeaturesSection: Datatype mappings


<strong>Cincom</strong> ORDB <strong>JDBC</strong> extension typesAlthough <strong>Cincom</strong> ORDB extensions are summarized here, see "4.<strong>Cincom</strong> ORDB Extensions" on page 28 for additional information.In addition, SQL datatypes also support the summarized <strong>JDBC</strong> extensions belowand shows their mappings to <strong>Cincom</strong> ORDB datatypes:♦♦♦The SQL datatype column lists the SQL datatypes that exist in thedatabase.The <strong>JDBC</strong> extensions for SQL datatypes column lists the types into which<strong>Cincom</strong> ORDB datatypes should map according to the <strong>JDBC</strong> 3.0 standard.The <strong>Cincom</strong> ORDB extensions—Java classes that represent SQL Datatypescolumn lists the ordbjava.jdbc.* Java types that correspond to each SQLdatatype in the database and that let you use the special features of the<strong>Cincom</strong> ORDB database objects.SQL datatypeObject Reference<strong>JDBC</strong> extensionsfor SQL datatypesjava.sql.Ref<strong>Cincom</strong> ORDB extensions—Java classesthat represent SQL datatypes♦♦ordbjava.jdbc.ordbGlo if thereference is for an instance of a glo, ora subclass of glo.ordbjava.jdbc.ordbObject if thereference is for an instance that is nota glo.Object Referencejava.sql.Struct♦ordbjava.jdbc.ordbGlo if thereference is for an instance of a glo, ora subclass of glo.♦ordbjava.jdbc.ordbObject if thereference is for an instance that is nota glo.Object Reference (GLO) java.sql.Blob ordbjava.jdbc.ordbGloObject Reference (GLO) java.sql.Clob ordbjava.jdbc.ordbGloCollections (sets, multisets,and sequences)java.sql.Array ordbjava.jdbc.ordbCollection<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 26Chapter: 3. Basic FeaturesSection: Datatype mappings


Error Messages and <strong>JDBC</strong>To handle exceptions, the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver throws ajava.sql.SQLException() for both database and <strong>JDBC</strong> Driver errors. Theexception object contains a text message describing the error.You can display the error messages with these methods:♦♦getMessage() — Returns the error message associated with the objectthat threw the exceptionprintStackTrace() — Prints this object name and its StackTrace to thespecified print streamThe following example uses both the getMessage() method and theprintStackTrace() method to return errors:catch(SQLException e);{System.out.println("exception: " + e.getMessage());e.printStackTrace();}The text of all error messages is internationalized. That is, they areavailable in all of the languages and character sets supported by<strong>Cincom</strong> ORDB. For a list of these error messages, refer to the <strong>Cincom</strong>BIfor SUPRA Messages and Codes, P25-9502.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 27Chapter: 3. Basic FeaturesSection: Error Messages and <strong>JDBC</strong>


4. <strong>Cincom</strong> ORDB ExtensionsIntroductionThis chapter describes <strong>Cincom</strong> ORDB extensions to standard <strong>JDBC</strong>, including thefollowing topics:♦♦♦♦<strong>Cincom</strong> ORDB <strong>JDBC</strong> packages and classesWorking with <strong>Cincom</strong> ORDB objects and object referencesCreating custom Java classes for <strong>Cincom</strong> ORDB objectsWorking with <strong>Cincom</strong> ORDB collectionsClasses of the ordbjava.jdbc packageThe following classes of the ordbjava.jdbc package include extensions to the<strong>JDBC</strong> interface that allow developers to use the advanced features of the<strong>Cincom</strong> ORDB database:♦♦♦ordbDriverordbObjectordbGlo (extends ordbObject)♦ ordbCollectionThe following sections describe these classes.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 28Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Introduction


Class ordbDriverThe ordbjava.jdbc.ordbDriver represents the <strong>Cincom</strong> ORDB databaseenvironment for the java application.♦♦Interfaces. The ordbDriver class implements the <strong>JDBC</strong> java.sql.Driverinterface.Extensions. In addition to the <strong>JDBC</strong> interface mentioned above, theordbDriver class also provides extensions for:- Pooling <strong>Cincom</strong> ORDB database connections- Setting the application name used in the <strong>Cincom</strong> ORDB server- Controlling the auto-commit default behavior for connectionsClass ordbObjectThe ordbjava.jdbc.ordbObject class and its subclass ordbjava.jdbc.ordbGlorepresent database instances and classes.♦ Interfaces. The ordbObject class implements the following <strong>JDBC</strong>interfaces:♦- java.sql.Ref- java.sql.Struct- java.sql.SQLInput- java.sql.SQLOutputExtensions. In addition to the <strong>JDBC</strong> interfaces mentioned above, theordbObject class also provides extensions for:- Inserting, updating, and deleting instances of a database class.- Retrieving attribute values from an instance of the database class.- Retrieving class attribute values from a database class.- Invoking methods on database instances and classes.The extensions allow application developers to work with the database objectsmore at the object interface level, rather than the SQL interface level.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 29Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Classes of the ordbjava.jdbc package


Class ordbGloThe ordbjava.jdbc.ordbGlo extends class ordbjava.jdbc.ordbObject andrepresent database instances derived from the <strong>Cincom</strong> ORDB glo system class.♦ Interfaces. In addition to the <strong>JDBC</strong> interfaces provided by ordbObject,ordbGlo implements the following <strong>JDBC</strong> interfaces:♦- java.sql.Blob- java.sql.ClobExtensions. The ordbGlo class also provides the same extensions as theordbObject class (see the extensions for "Class ordbObject" on page 29).Class ordbCollectionThe ordbjava.jdbc.ordbCollection class represents database collections.♦ Interfaces. The ordbCollection class implements the java.sql.Arrayinterface.♦Extensions. In addition to the Array interface, the ordbCollection classalso provides extensions for:- Creating new collections.- Inserting and deleting elements of a collection.- Working with heterogeneous collections.- Determining the number of elements in a collection.The extensions allow application developers to work with the databasecollection objects at the object interface level, rather than the SQL interfacelevel.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 30Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Classes of the ordbjava.jdbc package


Working with <strong>Cincom</strong> ORDB objects and object referencesThis section has these subsections:♦ Accessing attribute values♦ Inserting, deleting, and updating database instances♦ Invoking database methodsWithin the <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver, database object references arerepresented by an instance of a class (or an instance of a subclass) ofordbjava.jdbc.ordbObject.Accessing attribute valuesIn <strong>JDBC</strong>, the java.sql.Ref interface handles the object references. TheordbObject class implements the java.sql.Ref interface allowing generic <strong>JDBC</strong>applications to access and deal with object references without ever importingordbjava.jdbc.ordbObject into the application.The following sample code shows a generic <strong>JDBC</strong> application retrieving thebeach attribute (reference to a seashore object) from class resort, and thenaccessing the description from the seashore reference.Most of the remaining examples in this manual make use of a helperclass named demodbHelper to perform database connections. Thesource for the demodbHelper class is also included in your installation.This sample code may be found in the%ORDB%\demo\jdbc\samples\preparedStmtSample.java file://// This is a simple preparedStatement example//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;class preparedStmtSample {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (args, false);<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 31Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


prepare a statement that has an input parameterPreparedStatement pstmt = conn.prepareStatement("SELECT description FROM seashore WHERE " +"seashore.identity = ?");// Query the beaches of resortsStatement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery ("SELECT beach FROM resort");java.sql.Ref beach = null;while (rset.next ()) {// get the beach referencebeach = rset.getRef(1);// set the parameterpstmt.setRef(1, beach);// execute the prepared statementResultSet rset2 = pstmt.executeQuery();// fetch and display the result (should only be 1)rset2.next();String description = rset2.getString(1);System.out.println("description of beach (" + beach + "): " +description);// close the result setrset2.close();}// close statement and connectionstmt.close();pstmt.close();conn.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 32Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


Inserting, deleting, and updating database instancesWith standard <strong>JDBC</strong>, an application would have to make use of SQL to update,insert, and delete instances of the database.The class ordbjava.jdbc.ordbObject provides methods allowing the applicationdeveloper to insert, delete, and update instances of the database without usingSQL.The following sample code uses the ordbObject extensions to insert a newseashore object, delete an existing seashore instance, and update a resortobject to reference the new seashore.This sample code may be found in the%ORDB%\demo\jdbc\samples\ordbObject.java file://// This example demonstrates the use of the ordbObject methods to// create, delete, and update <strong>Cincom</strong> ORDB database instances.//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;class ordbObjectSample {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);// prepare a statement for displaying seashore description of aresortPreparedStatement pstmt = conn.prepareStatement("select beach.description from resort where resort = ?");// Query the first resort object referencesStatement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery ("SELECT identity FROMresort");<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 33Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


get the first resort referenceordbjava.jdbc.ordbObject resort = null;rset.next();// cast to ordbObject because we want to use the <strong>Cincom</strong> ORDBjdbc extensionsresort = (ordbjava.jdbc.ordbObject)rset.getRef(1);rset.close();// get the beach reference from the resort (instance ofseashore)ordbjava.jdbc.ordbObject beach =(ordbjava.jdbc.ordbObject)resort.getAttributeValue("beach");// display the descriptionpstmt.setRef(1, resort);rset = pstmt.executeQuery();rset.next();System.out.println(" beach description of first resort beforeupdate: " +rset.getString(1));rset.close();//delete the seashore instancebeach.deleteInstance();// create a new seashore instance (not yet in the database)beach = new ordbjava.jdbc.ordbObject(conn, "seashore");// update the attributes with valuesbeach.setAttributeValue("description", new String("newseashore"));beach.setAttributeValue("has_lifeguard", new String("yes"));beach.setAttributeValue("has_beach_chairs", new String("no"));// add the instance to the databasebeach.updateInstance();// update resort to reference the newly created seashoreinstanceresort.setAttributeValue("beach", beach);resort.updateInstance();<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 34Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


display the descriptionpstmt.setRef(1, resort);rset = pstmt.executeQuery();rset.next();System.out.println(" beach description of first resort afterupdate: " +rset.getString(1));rset.close();pstmt.close();stmt.close();conn.close();}}The previous example shows the following steps that an application mustperform in order to use the ordbObject methods to insert and/or update adatabase instance:1. Acquire an ordbObject (either existing object for update, or using theordbObject(Connection, className) constructor for insert).2. Make calls to setAttributeValue() method to update the attributes of theobject. These updates are actually performed on a template of thedatabase instance.3. Call updateInstance() method to transmit the changes to the database. Thiswill result in an insert of a new object, or the update of an existing objectdepending on how the ordbObject instance was acquired in step 1.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 35Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


Invoking database methodsYou can use the invokeMethod and invokeClassMethod operations to callinstance and class methods on the database.Instance methods. When invoking instance methods, you must provide:♦The method name♦ An array of ordered arguments for the methodClass methods. When invoking class methods, you must provide:♦♦The database connection objectThe class name♦ The name of the method and an array of ordered arguments for the methodExample. The following example demonstrates calling both class and instancemethods on the location class of demodb. This sample code may be found inthe %ORDB%\demo\jdbc\samples\methodSample.java file://// This example demonstrates the use of ordbObject to invoke databasemethodspackage demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import java.awt.*;import ordbjava.jdbc.*;class methodSample {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);// Find the location instance for "Holiday Inn" by making// use of the v5_find_lodging_named class method of location// Set up the argument for the database methodObject[] method_argv = new Object[1];method_argv[0] = "Holiday Inn";<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 36Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


invoke the methodordbObject location = (ordbObject)ordbObject.invokeClassMethod(conn,"location", "v5_find_lodging_named", method_argv);// Now use the instance method to find out how far the location is fromthe equatorString distance =(String)location.invokeMethod("v5_distance_from_equator", null);System.out.println("Holiday Inn resort is " + distance);conn.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 37Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB objects and object references


Creating custom Java classes for <strong>Cincom</strong> ORDB objectsCustom mapping is a powerful tool that allows Java classes to map to databaseclasses. The <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver provides custom mapping functions thatcan automatically generate instances of a custom Java class from a databaseobject reference.This section discusses:♦♦♦♦♦♦♦Generating Java classes from a database schemaGenerating Java classes with the CustomMappingDlg classAnnotated examples of custom mapped classesRelating Java classes to database class namesControlling when custom mapping occursInserting, deleting, and updating with custom mappingWriting your own custom mapping classes<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 38Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Generating Java classes from a database schemaThe ddltojava utility generates custom Java classes from a database schema.The utility processes the schema (.sch) file produced by the unloaddb utility,and generates Java classes for use in your applications.Even if you still have your schema file, <strong>Cincom</strong> recommends that you run theunloaddb utility to generate a new schema file. This ensures that all systemclasses are included in the schema used by the ddltojava utility.The name of the Java classes will be the database class name with a “j” prefix.For example, a database class named location will generate the Java classjlocation.java.The syntax of the ddltojava utility command is:ddltojava [ -d output_directory] [-p package_name][-preclass_prefix] [-v] schemafilewhere:-d output_directory Optional. This parameter is the name of an existingdirectory that will contain the resulting java files. Thedefault output location is the current workingdirectory.-p package_name This parameter influences the generated files. If youspecify a package name of sample.demodb, then thejava classes will be written tooutput_path\sample\demodb directory. Thesample\demodb directory will be created if it does notexist.-pre class_prefixOptional. This parameter is the prefix of thegenerated Java classes. For example, if you specify –pre java then, the names of the Java classes will be thenames in the schema preceded by the word java.-v Optional. This parameter is for the verbose mode. Itenables more messages.schemafileRequired. This parameter is the name of the schemadefinition file produced by the unloaddb utility.Generating Java classes with the CustomMappingDlg classThe CustomMappingDlg class contained in the %ORDB%\ordbjava.jar file is aJava swing application that you can use to generate java class files that map toyour <strong>Cincom</strong> ORDB classes. The tool can be invoked by the following command:java –cp %ORDB%\ordbjava.jar CustomMappingDlg<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 39Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Annotated examples of custom mapped classesThe class jresort.java and class jaccommodations.java were originallygenerated by the ddltojava utility and then comments in bold(// ... comment) were added to describe various items in the classes.The java classes that map to the demodb schema may be found in the%ORDB%\demo\jdbc\samples directory. All of the custom mapped classes arelocated in the demo.jdbc.samples package.class jresort.javaThe following is a class jresort.java example:package sample.demodb;// The option "–p sample.demodb –pre j" was used when ddltojava utilitywas invokedimport java.sql.*;import java.math.*;import ordbjava.jdbc.*;/*** jresort.java is a tool generated Java programming* language class for custom mapping of the* persistent class resort*/// The tool generates comments in the java class.public class jresort extends jaccommodations {// Single inheritance is supported by the tool. If the database class has// multiple inheritance, or attribute ordering is changed, the tool will// flatten the mapping into one java class.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 40Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


See the jaccommodations class below for more comments.public ordbCollection cabins;public ordbObject beach;public String has_daycare;public ordbCollection activities;public ordbGlo sounds_of_the_caribbean;// The database attributes are marked public, the datatypes are set based// on the default data type mapping between the types and the jdbc types.// Note that the beach attribute is of type ordbObject, the// sounds_of_the_Caribbean attribute is of type ordbGlo (subclass of// ordbObject). Also note that the attributes cabins and activities are// of type ordbCollection.private static String ddl_class_name = "resort";/** This default constructor is only used* by the custom mapping*/public jresort(){ }// The jdbc driver will use the above constructor and then invoke the// readSQL method to get the attribute values from the database./** Constructor for creating new resort* in the database.* @param con the connection obtained fromDriverManager.getConnection()*/public jresort(Connection con) throws SQLException {super(con, ddl_class_name);}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 41Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


The above constructor can be used by the application developer to// create a new database template instance of the class./** This constructor is internally used by subclasses of jresort*/protected jresort(Connection con, String ddl_name) throws SQLException{super(con, ddl_name);}/*** This method does the mapping from database class resort* to Java programming language class jresort.* It is internally called by the <strong>JDBC</strong> driver.* @see java.sql.SQLData#readSQL* @see java.sql.SQLInput*/public void readSQL(SQLInput stream, String type) throws SQLException{super.readSQL(stream, type);// Invoke the superclass method to get the values from attributes// defined by the superclass.cabins = (ordbCollection)stream.readArray();beach = (ordbObject)stream.readRef();has_daycare = stream.readString();activities = (ordbCollection)stream.readArray();sounds_of_the_caribbean = (ordbGlo)stream.readRef();}/*** This method maps the Java programming language class* jresort back to the database class resort.* @param stream an output stream that is an instance of interface* SQLOutput, to which data will be written.* @see java.sql.SQLData#writeSQL* @see java.sql.SQLOutput*/<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 42Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


}// The application needs to call this method to insert or update// the database instance associated with this object.public void writeSQL(SQLOutput stream) throws SQLException {super.writeSQL(stream);// Invoke the superclass method to write the values from attributes// defined by the superclass.stream.writeArray(cabins);stream.writeRef((Ref)beach);stream.writeString(has_daycare);stream.writeArray(activities);stream.writeRef((Ref)sounds_of_the_caribbean);}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 43Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


class jaccommodations.javaThe following is a class jaccommodations.java example:package sample.demodb;import java.sql.*;import java.math.*;import ordbjava.jdbc.*;/*** jaccommodations.java is a tool generated Java programming* language class for custom mapping of the* persistent class accommodations*/public class jaccommodations extends ordbObject implements SQLData {// All custom mapped classes must be a subclass of ordbObject.// ordbObject will hold the object identifier and also implements many// methods that are used by custom mapping.public String off_season;public ordbCollection rooms;public int number_of_restaurants;public int number_of_pools;public String allows_children;public Time checkout_time;public String country;public String cost;public String name;public ordbObject photo;protected String sql_type;private static String ddl_class_name = "accommodations";/** This default constructor is only used* by the custom mapping*/<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 44Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


public jaccommodations(){ }/** Constructor for creating new accommodations* in the database.* @param con the connection obtained from* DriverManager.getConnection()*/public jaccommodations(Connection con) throws SQLException {super(con, ddl_class_name);}/** This constructor is internally used by subclasses of* jaccommodations*/protected jaccommodations(Connection con, String ddl_name) throwsSQLException {super(con, ddl_name);}/*** This is a SQLData method that is internally called by the driver.* @see java.sql.SQLData#getSQLTypeName*/public String getSQLTypeName() {return sql_type;}/*** This method does the mapping from database class accommodations* to Java programming language class jaccommodations.* It is internally called by the <strong>JDBC</strong> driver.* @see java.sql.SQLData#readSQL* @see java.sql.SQLInput*/<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 45Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


public void readSQL(SQLInput stream, String type) throws SQLException{}sql_type = type;off_season = stream.readString();rooms = (ordbCollection)stream.readArray();number_of_restaurants = stream.readInt();number_of_pools = stream.readInt();allows_children = stream.readString();checkout_time = stream.readTime();country = stream.readString();cost = stream.readString();name = stream.readString();photo = (ordbObject)stream.readRef();/*** This method maps the Java programming language class* jaccommodations back to the database class accommodations.* @param stream an output stream that is an instance of interface* SQLOutput, to which data will be written.* @see java.sql.SQLData#writeSQL* @see java.sql.SQLOutput*/public void writeSQL(SQLOutput stream) throws SQLException {stream.writeString(off_season);stream.writeArray(rooms);stream.writeInt(number_of_restaurants);stream.writeInt(number_of_pools);stream.writeString(allows_children);stream.writeTime(checkout_time);stream.writeString(country);stream.writeString(cost);stream.writeString(name);stream.writeRef((Ref)photo);}/**<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 46Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


* Database method.*/// The mapping tool generates java methods to expose database methods.public int overpriced( ) throws SQLException {String method_name = "overpriced";Object retVal;retVal = invokeMethod(method_name, null);return ((Integer)retVal).intValue();}/*** Database method.*/public int v5_overpriced( ) throws SQLException {String method_name = "v5_overpriced";Object retVal;retVal = invokeMethod(method_name, null);return ((Integer)retVal).intValue();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 47Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Relating Java classes to database class namesThe type map relates a Java class to a <strong>Cincom</strong> ORDB class name, which is aone-to-one mapping. This one-to-one mapping is stored in a hash table as akey-value pair. When you request custom mapping to be performed on a<strong>Cincom</strong> ORDB object reference, the <strong>JDBC</strong> driver considers the type map todetermine which Java class to use to materialize the data from the databaseobject. Once the object data is materialized as a Java object, you can updatethe attributes in the Java object. The changes can then be persisted in thedatabase by invoking the writeSQL() method of the java object. The driverhandles the actual conversion between SQL and Java.The Java application programmer is responsible for providing a type map classthat implements java.util.Dictionary. For example,java.util.Hashtable implements Dictionary.The type map class must implement a put() method used to enter eachmapping entry that relates a Java class to a database class name. The put()method must be implemented to accept a keyword-value pair, where thekeyword is an database class name and the value is the Java class object.Each connection object has an attribute for an associated type map object.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 48Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Adding entries. The following general steps add entries to an existing typemap:1. Obtain the type map you want to maintain. This can be a newly createdtype map, or an existing map. For example:java.util.Dictionary myMap = conn.getTypeMap();where getMapType() method on the Connection object conn returns themyMap Dictionary object2. Use the Dictionary object’s put() method to add entries to the map. Theput() method takes two arguments.a. A database class name string:myMap.put(dbClassName, classObject);where:- dbClassName is a string that represents the name of the class inthe database- classObject is the Java class object to which maps to thedatabase classb. The name of the Java class object to which you want to map it. Getthe java class object with the class.forName() method. You can rewritethe put() method as:myMap.put(dbClassName, class.forName(className));For example, if you have a resort class defined in the database schema,then map it to a Java class defined as jresort with this statement:myMap.put("resort", class.forName("jresort"));The map now has an entry that maps the resort class in the database tothe jresort Java class.3. When you finish adding entries to the map, use the Connection object’ssetTypeMap() method to overwrite the connection’s existing type map. Forexample:conn.setTypeMap(myMap);where setTypeMap() overwrites the connection’s original map withmyMap<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 49Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Controlling when custom mapping occursOnce your Java application has a database object reference, there are severalmethods to materialize the referenced database object as an instance of thecustom mapped class:The java.sql.ResultSet.getObject method♦♦The ordbObject.getObject methodThe getAttributes method of the java.sql.Struct interfaceUsing the java.sql.ResultSet.getObject MethodThe generic <strong>JDBC</strong> way to request custom mapping is to use the getObjectmethod of the java.sql.ResultSet interface.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver performs custom mapping when the getObject()method invokes the ResultSet column that contains an object reference. Usethe getRef() method if you do not want custom mapping performed.The following example assumes that the default type map associates thedatabase class “seashore” with the java class jseashore:...ResultSet rset = stmt.executeQuery ("SELECT name,beach FROM resortWHERE beach IS NOT NULL");// get the beach as an instance of the custom mapped class// jseashore.javajseashore beach = null;while (rset.next ()) {beach = (jseashore)rset.getObject(2));// Internally the <strong>JDBC</strong> Driver performs these actions:// 1. If the database value is NOT an oid, then// generate a java object of appropriate type and// return.// 2. The database value is an oid, what we really have is// an instance of the ordbObject class.// 3. Check the type map (default or passed as parm) to see// if the database class has a custom java class.// If there is no custom class, return the ordbObject// to application as a (by casting to) java.sql.Struct// 4. If there is a custom map, instantiate an instance of the<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 50Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


custom mapped class, then.// 5. Invokes the readSQL() method (of the SQLData// interface) on the custom class.// (The SQLData interface must be implemented by a custom// class.)// 6. When readSQL is done, the java instance will be// populated with the attribute data from the database.System.out.println("beach description of resort " +rset.getString(1) + " :" + beach.description);}...Using the ordbObject.getObject methodThe ordbObject class also supports the getObject method. When you call thegetObject method of an instance of ordbObject, the <strong>JDBC</strong> driver willmaterialize the database object referenced by the ordbObject as an instanceof the custom mapped java class. If the type map (either the default, or passedas a parameter) does not contain a mapping for the database class that theordbObject is an instance of, then the getObject method will return theordbObject as a java.sql.Struct (via a cast).The following example assumes that the default type map associates thedatabase class “seashore” with the java class jseashore, and the database class“resort” with the java class jresort:ResultSet rset = stmt.executeQuery ("SELECT resort.IDENTITY resortWHERE beach IS NOT NULL");jresort resort = null;while (rset.next ()) {resort = rset.getObject(1));jseashore seashore = resort.beach.getObject();System.out.println("beach description of resort " +resort.name + " :" + seashore.description);}...<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 51Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Using the getAttributes method of the java.sql.StructinterfaceBy default, the getAttributes methods of the java.sql.Struct interface(implemented by ordbObject) will return database object references as typejava.sql.Ref.The static method ordbObject.setAutoPerformCustomMapping directsgetAttributes whether or not custom mapping should perform on databasereferences.The following example uses custom mapping with and without automaticinvocation. This sample code may be found in the%ORDB%\demo\jdbc\samples\customMappingSample1.java file://// This sample program demonstrates the use of custom mapping//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import java.awt.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass customMappingSample {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);try{// add a type map to relate java class jseashore to database class// seashore.conn.getTypeMap().put("seashore",Class.forName("demo.jdbc.samples.jseashore"));} catch(ClassNotFoundException e){System.out.println("***Caught SQLException: " + e.getMessage());}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 52Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Turn off AutoPerformCustomMapping (the default is off)ordbjava.jdbc.ordbObject.setAutoPerformCustomMapping(false);Statement stmt = conn.createStatement();// build result set of resort referencesResultSet rset = stmt.executeQuery("SELECT resort.IDENTITY from resort WHERE beach IS NOT NULL");// We are using the <strong>Cincom</strong> ORDB extensions, so we will ask forordbObjectordbjava.jdbc.ordbObject resort = null;while (rset.next ()) {resort = ((ordbjava.jdbc.ordbObject)rset.getRef(1));// ordbObject implements the java.sql.Struct interface, so we// can call the Struct methodsObject [] resortAttrs = resort.getAttributes();// Now the array resortAttrs has the values of the resort// instance attributes. The 1st attribute value is// in resortAttrs[0].// Here is the mapping based on the demodb schema:// resortAttrs Index Attribute Name// ---------------- ---------------------------// 0 off_season// 1 rooms// 2 number_of_restaurants// 3 number_of_pools// 4 allows_children// 5 checkout_time// 6 country// 7 cost// 8 name// 9 photo// 10 cabins// 11 beach// 12 has_daycare<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 53Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


13 activities// 14 sounds_of_the_carribeanboolean customMapSwitch = ordbObject.getAutoPerformCustomMapping();jseashore seashore = null;if (!customMapSwitch) {// if custom mapping is off, the beach reference// contained in resortAttrs[11] is an instance of// ordbObject that has not been instantiated as a java// object. We can use the getObject method of// ordbObject to explicitly perform the custom mapping.ordbObject beachRef = (ordbObject)resortAttrs[11];seashore = (jseashore) beachRef.getObject();} else {// Custom mapping is on, resortAttrs[11] contains// a jseashore instance.seashore = (jseashore)resortAttrs[11];}System.out.println("beach description of resort " + resortAttrs[8] +": "+ seashore.description);// Toggle the auto perform custom mapping switchordbObject.setAutoPerformCustomMapping(!customMapSwitch);}rset.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 54Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Inserting, deleting, and updating with custom mappingCustom mapped java class methods allow the application developer to insert,delete, and update instances of the database without using SQL.The following sample code uses custom mapping to insert a new seashoreobject, delete an existing seashore instance, and update a resort object toreference the new seashore.This sample code may be found in the%ORDB%\demo\jdbc\samples\customMappingSample2.java file:These samples assume that the default type map defines all the custom mapsrequired.//// This sample program demonstrates the use of custom mapping//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass customMappingSample2 {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);try{// add type maps for custom mapping.conn.getTypeMap().put("seashore",Class.forName("demo.jdbc.samples.jseashore"));conn.getTypeMap().put("resort",Class.forName("demo.jdbc.samples.jresort"));} catch(ClassNotFoundException e){System.out.println("***Caught SQLException: " + e.getMessage());<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 55Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


}Statement stmt = conn.createStatement();ResultSet rset = stmt.executeQuery ("SELECT identity FROM resort");// get the first resort referenceordbjava.jdbc.ordbObject resortRef = null;rset.next();resortRef = (ordbjava.jdbc.ordbObject)rset.getRef(1);rset.close();// get the resort as custom mapped classjresort resort = (jresort)resortRef.getObject();// get the beach using custom mappingjseashore seashore = (jseashore)resort.beach.getObject();System.out.println(" beach description of first resort before update: "+seashore.description);// delete the seashore instanceseashore.deleteInstance();// create a new seashore instance template(not yet in the database)seashore = new jseashore(conn);// update the attributes with valuesseashore.description = "new seashore";seashore.has_lifeguard = "yes";seashore.has_beach_chairs = "no";// add the instance to the databaseseashore.writeSQL(seashore);// update resort to reference new beachresort.beach = seashore;resort.writeSQL(resort);<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 56Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


displaying seashore description after the updatePreparedStatement pstmt = conn.prepareStatement("select beach.description from resort where resort = ?");pstmt.setRef(1, resort);rset = pstmt.executeQuery();rset.next();System.out.println(" beach description of first resort after update: " +rset.getString(1));rset.close();pstmt.close();stmt.close();conn.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 57Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


In the previous example, the application had to perform the following steps inorder to use custom mapping to insert and/or update a database instance:1. Acquire a custom mapped instance (either existing object for update, orusing the constructor that takes the Connection as a parameter for insert).2. Modify the attributes of the custom mapped class.3. Invoke the writeSQL method passing the custom mapped instance as anargument. (This is possible since the custom mapped instance is a subclassof ordbObject, and ordbObject implements the SQLInput and SQLOuputinterfaces.)Writing your own custom mapping classesAlthough the ddltojava utility is the easiest way to generate java classes foruse with custom mapping, you can write your own custom java classes.Custom java classes used for mapping to <strong>Cincom</strong> ORDB classes must:♦♦Implement the SQLData interfaceExtend the ordbjava.jdbc.ordbObject classUnderstanding the SQLData interfaceThe SQLData interface defines methods that translate between SQL and Javafor <strong>Cincom</strong> ORDB database objects.If you create a custom Java class that implements SQLData, you must provide areadSQL() method and writeSQL() method as defined by the SQLData interface.The <strong>JDBC</strong> driver calls your readSQL() method to read a stream of data valuesfrom the database and populate an instance of your custom Java class.Typically, the driver would use this method as part of an ResultSet.getObject()call.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver never invokes the writeSQL() method,but application developers can invoke the writeSQL() method to insertand/or update instances in the database.Understanding the SQLInput and SQLOutput interfaces. The class,ordbObject class of the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver, implements the SQLInputand SQLOutput interfaces. It is not necessary to implement the SQLOutput orSQLInput objects. The <strong>JDBC</strong> drivers will do this for you.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 58Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Implementing readSQL() and writeSQL() methods. When you create yourcustom Java class that implements SQLData, you must also implement thereadSQL() and writeSQL() methods.♦readSQL() method. You must implement readSQL() as follows:public void readSQL(SQLInput stream, String sql_type_name)throws SQLException- readSQL() must take as input an SQLInput stream and a string thatindicates the SQL type name of the data (in other words, the name ofthe <strong>Cincom</strong> ORDB class name, such as seashore).- When your Java application calls getObject(), the <strong>JDBC</strong> driver createsan SQLInput stream object (an instance of ordbObject) and populates itwith data from the database. The driver can also determine the SQLtype name of the data when it reads it from the database. When thedriver calls readSQL(), it passes in these parameters.- For each Java datatype that maps to an attribute of the <strong>Cincom</strong> ORDBobject, readSQL() must call the appropriate readXXX() method of theSQLInput stream that is passed in.- For example, if you are reading a database object that has a CHARattribute followed by an INTEGER attribute, you must have areadString() call and a readInt() call in your readSQL() method. <strong>JDBC</strong>calls these methods according to the order that the attributes appearin the schema definition of the <strong>Cincom</strong> ORDB class.- readSQL() assigns the data that the readXXX() methods read andconvert to the appropriate fields or elements of your custom Javaclass.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 59Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


♦writeSQL() method. You must implement writeSQL() as follows:public void writeSQL(SQLOutput stream) throws SQLException- writeSQL() must take as input an SQLOutput stream.- When your Java application calls writeSQL(), the <strong>JDBC</strong> driver creates anSQLOutput stream object and populates it with data from your customJava class. When the driver calls writeSQL(), it passes in this streamparameter.- For each Java datatype that maps to an attribute of the <strong>Cincom</strong> ORDBclass, writeSQL() must call the appropriate writeXXX() method of theSQLOutput stream that is passed in.- For example, if you are writing to objects that have a CHAR attributefollowed by an INTEGER attribute, then you must have a writeString()call and a writeInt() call in your writeSQL() method. These methodsmust be called according to the order that attributes appear in theschema definition of the <strong>Cincom</strong> ORDB class.- writeSQL() must then write the data converted by the writeXXX()methods to the SQLOutput stream so it can be written to the databaseonce you execute the prepared statement.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 60Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Creating custom Java classes for <strong>Cincom</strong> ORDB objects


Working with <strong>Cincom</strong> ORDB collectionsThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver exposes database collections as instances of theclass ordbjava.jdbc.ordbCollection. The ordbCollection class implements thejava.sql.Array interface, and provides additional methods to make it easier towork with <strong>Cincom</strong> ORDB collections.The following sections discuss how to:♦ Retrieve a collection and its elements♦♦♦♦Work with heterogeneous collectionsHomogeneous collections and Java primitive arraysCreate and modify collectionsCollections and custom mapping♦ Freeing <strong>Cincom</strong> ORDB workspace storage used by ordbCollectionsThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver exposes database collections as instances of theclass ordbjava.jdbc.ordbCollection. The ordbCollection class implements thejava.sql.Array interface, and provides additional methods to make it easier towork with <strong>Cincom</strong> ORDB collections.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 61Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Retrieving a collection and its elementsWhen you retrieve a collection, you get an ordbjava.jdbc.ordbCollection objectwhere each returned array element is a materialized Java array object or aresult set object.Once you have the collection in an ordbCollection object, you can retrieve thedata using one of the overloaded methods of the java.sql.ARRAY interface:♦♦getArray() - The getArray() methods retrieve the elements of the collection(or a subset of the collection) into a java array. The elements areconverted to the Java types corresponding to the SQL type of the data inthe collection.getResultSet() - The getResultSet() methods return a result set thatcontains elements of the collection (or a subset of the collection)designated by the ARRAY object. The result set contains one row for eachcollection element, with two columns in each row. The first column storesthe index into the database collection for that element, and the secondcolumn contains the element value.Retrieving all of an array’s elementsIf you use getArray() to retrieve an array of primitive datatypes, then ajava.lang.Object that contains the element values is returned. The elements ofthis array are of the Java type corresponding to the SQL type of the elements.For example,BigDecimal[] values=(BigDecimal[]) intArray.getArray();where intArray is an ordbjava.jdbc.ordbCollection corresponding to adatabase collection of type NUMERIC.Similarly, if you use getResultSet() to return an array of primitive datatypes,then the <strong>JDBC</strong> drivers return a ResultSet object that contains, for eachelement, the index into the array for the element and the element value. Forexample:ResultSet rset= intArray.getResultSet();In this case, the result set contains one row for each array element, with twocolumns in each row. The first column stores the index into the array; thesecond column stores the BigDecimal element value.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 62Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Retrieving a subset of an array’s elementsTo retrieve a subset of the array, you can pass in an index and a count toindicate where in the array you want to start and how many elements you wantto retrieve. For example:Object object = arr.getArray(index, count);And using getResultSet():ResultSet rset= arr.getResultSet(index, count);The following example shows various uses of methods getArray() andgetResultSet().This sample code may be found in the%ORDB%\demo\jdbc\samples\collectionSample1.java file://////// This sample demonstrates the use of the java.sql.Array interface with// <strong>Cincom</strong> ORDB database collections.//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass collectionSample1 {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);Statement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery ("SELECT name, activities FROMresort");<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 63Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


while (rset.next()) {// activities is a set of stringsjava.sql.Array activitySet = rset.getArray(2);// Now get and display all the elements of the activity setObject [] allActivities = ((Object [])activitySet.getArray());if (allActivities != null) {// Array.getArray returns null if the database// collection is empty.System.out.println("All Activities for resort " +rset.getString(1));for (int i = 0; i < allActivities.length; i++)System.out.println("\t" + allActivities[i]);}elseSystem.out.println("No activities listed for resort\n" +rset.getString(1));// Now get and display elements 2 thru 4 of the activity set,// but this time use a result set. (start at 2, length of 3)java.sql.ResultSet rsActivity = activitySet.getResultSet(2,3);while (rsActivity.next())System.out.println("Resort " + rset.getString(1) +" has activity " + rsActivity.getString(2) +" in position " + rsActivity.getInt(1) +" of the activities collection attribute\n");}// Clean up workspace storage used by the collectionif (activitySet != null)((ordbCollection)activitySet).free();rset.close();stmt.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 64Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Working with heterogeneous collectionsThe java.sql.Array interface assumes that all elements in the array have thesame domain. Since <strong>Cincom</strong> ORDB collections can be heterogeneous, theordbCollection class provides additional methods for dealing withheterogeneous collections. These methods are:♦♦♦isHomogeneous() - Returns true if the elements of the database collectionare of the same domain.getBaseType(int index) - Returns the <strong>JDBC</strong> type (from java.sql.Types) ofthe specified element. (The first collection element is at index 1.)getBaseTypeName(int index) - Returns the database domain string for thespecified element.The following example demonstrates these methods and can be found in the%ORDB%\demo\jdbc\samples\collectionSample2.java file://// This example demonstrates the use of ordbCollection methods to deal// with heterogeneous <strong>Cincom</strong> ORDB collections.//package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass collectionSample2 {public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);/* select a heterogeneous set */Statement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery ("SELECT name, rooms FROM resort");<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 65Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


ordbCollection rooms = null;while (rset.next()) {rooms = (ordbCollection)rset.getArray(2);if (rooms != null && rooms.getSize() > 0) {System.out.println("\nResort " + rset.getString(1) +" has the following types in the rooms attribute");// view the collection as a result setResultSet roomRS = rooms.getResultSet();// position on first collection elementroomRS.next();// loop through each element and obtain its type and print the data// Note: ordbCollection.getSize() returns the// number of elements in the database collectionfor (int i = 1; i


Homogeneous collections and Java primitive arraysThe getArray methods of the java.sql.Array interface specify that arrays ofprimitive data types shall be returned as a java array of primitive types.This causes problems if the underlying homogeneous <strong>Cincom</strong> ORDB collectionhas elements that are null. The java primitive cannot represent null.We have provided two methods that allow you to deal with this issue:♦♦getAlwaysReturnObjects() - Allows you to determine if the getArraymethods can return primitive arrays or will always return object arrays.setAlwaysReturnObjects(boolean boolVal) - Allows you to indicate if thegetArray method should always return java Object arrays. (Primitives arereturned as java objects within this array.)The getArray method will throw an exception when attempting to transfer anull into a primitive.Default setting is for getArray to either return a primitive array or object array.Heterogeneous database collections always return array of objects.This example demonstrates the use of these methods and can be found in the%ORDB%\demo\jdbc\samples\collectionSample3.java file://// This sample demonstrates the ordbCollection methods that deal with// homogeneous collections of primitive datatypes.package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass collectionSample3 {<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 67Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);// get a homogeneous collection of a primitive data typeStatement stmt = conn.createStatement();stmt.executeUpdate("create class primitive(int_set set of int)");stmt.executeUpdate("insert into primitive " +"values({1,2,3,4,5,null})");ResultSet rs = stmt.executeQuery("select int_set from primitive");rs.next();ordbCollection intSet = (ordbCollection)rs.getArray("int_set");rs.close();try {// get first 5 elements into int array (skip null)int [] intArray = (int [])intSet.getArray(1, 5);for (int i = 0; i < intArray.length; i++)System.out.println("element: " + i + " int value: " + intArray[i]);} catch (SQLException e) {System.out.println("Error, should not get to this exception");}// now try to include the null, handle the exceptiontry {int [] intArray = (int [])intSet.getArray();} catch (SQLException e) {// try as object arraySystem.out.println("Exception: " + e.getMessage());System.out.println("try again as array of objects");intSet.setAlwaysReturnObjects(true);Object [] IntegerArray = (Object [])intSet.getArray();for (int i = 0;i < IntegerArray.length; i++)System.out.println("element" + i + " object value: " +(Integer)IntegerArray[i]);}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 68Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Clean up <strong>Cincom</strong> ORDB workspace used by collectionif (intSet != null)intSet.free();stmt.close();conn.close();}}Creating and modifying collectionsThe ordbCollection class provides methods that allow you to create andmaintain your database collections. The methods modify a copy of thecollection within the workspace. After creating and/or updating a collectionwith these methods, you have to update the database attribute with themodified collection. This can be done with SQL using thejava.sql.PreparedStatement, or by using the setAttributeValue() method ofordbObject.The methods of the ordbCollection class are:♦♦♦♦ordbCollection(Connection con)deleteValue(int index)insertValue(Object javaObj, int <strong>JDBC</strong>type, int index)removeNulls()ordbCollection(Connection con)The ordbCollection(Connection con) constructor creates an empty collection.Instances of ordbCollection created with this constructor are heterogeneousand can accept any type of element data. The database performs Typevalidation when the new collection is associated with the database attribute.deleteValue(int index)The deleteValue(int index) method removes the collection element at theindex position. All elements to the right of the index will be shifted oneposition to the left.Be careful when using loops! The size of the collection will decrease by 1.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 69Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


insertValue(Object javaObj, int <strong>JDBC</strong>type, int index)The insertValue(Object javaObj, int <strong>JDBC</strong>type, int index) inserts the valuecontained in javaObj of type <strong>JDBC</strong>Type into the collection at location index.The value is always inserted at the position given. If the index is beyond thesize of the collection, null elements will be inserted to fill in the “holes”. Ifthere is a value in the index position, all values from the current index positionwill be shifted right one position to make room for the new value. The size ofthe collection will increase by one or more elements.removeNulls()The removeNulls() method will delete null elements from the collection. Thisincludes values that are null as well as object references that point to deletedreferences. The size of the collection may decrease.The following example shows the use of these methods and can found in the%ORDB%\demo\jdbc\samples\collectionSample4.java file:package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass collectionSample4{public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);// Create a new collection leaving some "holes"ordbCollection newActivities = new ordbCollection(conn);String activity = "Activity 1";newActivities.insertValue(activity,Types.VARCHAR,1);activity = "Activity 3";newActivities.insertValue(activity,Types.VARCHAR,3);activity = "Activity 5";newActivities.insertValue(activity,Types.VARCHAR,5);<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 70Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


display the size and contents of the collectionSystem.out.println("Size before remove nulls: " +newActivities.getSize());ResultSet rs=newActivities.getResultSet();while (rs.next())System.out.println("Collection element " + rs.getInt(1) +" value: " + rs.getString(2));rs.close();// Use removeNulls method to delete "holes", then// display contents (using Array instead of// resultSet this time just for example)newActivities.removeNulls();System.out.println("Size after remove nulls: " +newActivities.getSize());Object [] vals = (Object [])newActivities.getArray();int elem = 0;for (elem = 0; elem < vals.length; elem++)System.out.println("Array element " + elem + " value: " +(String)vals[elem]);// Delete the first element and display size & contentsnewActivities.deleteValue(1);System.out.println("Size after delete element: " +newActivities.getSize());rs = newActivities.getResultSet();while (rs.next())System.out.println("Collection element " + rs.getInt(1) +" value: " + rs.getString(2));rs.close();<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 71Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Example using the Array as input parameterString resortName = "newResort";PreparedStatement stmt =conn.prepareStatement("insert into" +" resort(name,activities) values(?, ?)");stmt.setString(1, resortName);stmt.setArray(2, newActivities);stmt.executeUpdate();stmt.close();// display the new resort activitiesStatement stmt1 = conn.createStatement();rs = stmt1.executeQuery("select a.activity from " + "resort,table(activities) as a(activity)" +" where name = 'newResort'");System.out.println("activities in newResort follow:");while (rs.next())System.out.println(rs.getString(1));rs.close();stmt1.close();stmt.close();// Clean up <strong>Cincom</strong> ORDB workspace storage used by the collectionif (newActivities != null)newActivities.free();// close the connectionconn.close();}}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 72Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Collections and custom mappingBy default, the getArray methods of the java.sql.Array interface (implementedby ordbCollection) will return database object references as type java.sql.Ref.The static method ordbCollection.setAutoPerformCustomMapping can be usedto indicate whether getArray should perform custom mapping on databasereferences. The following example shows both behaviors. This sample can befound in the %ORDB%\demo\jdbc\samples\collectionSample5.java file:package demo.jdbc.samples;import java.sql.*;import java.math.*;import java.io.*;import ordbjava.jdbc.*;import java.util.HashMap;//import for custom mappingclass collectionSample5{public static void main (String args []) throws SQLException{// Connect to the demodb database without autocommit enabled.Connection conn = demodbHelper.makeConnection (false);Statement stmt = conn.createStatement();// Build a type map to relate java class jseashore to database class// seashore.try{conn.getTypeMap().put("seashore",Class.forName("demo.jdbc.samples.jseashore"));} catch(ClassNotFoundException e){System.out.println("***Caught SQLException: " + e.getMessage());}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 73Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


create a new collection of seashore referencesordbCollection seashores = new ordbCollection(conn);ResultSet rs = stmt.executeQuery("select beach from resort");while (rs.next())seashores.insertValue(rs.getRef(1),Types.REF,1);Object [] beachRefs = (Object [])seashores.getArray();// custom mapping was not performed automatically// The following loop uses three different ways to// obtain the description from the seashore instanceObject [] beachAttrs = null;for (int i=0; i < beachRefs.length; i++) {// One way is to use the java.sql.Struct interface// (description is 1st attribute in seashore schema definition)beachAttrs = ((Struct)beachRefs[i]).getAttributes();System.out.println("beach description(Struct): " + beachAttrs[0] );// Another way is to explicitly invoke custom mapping// This of course assumes that we have a mapping definedjseashore beachx =(jseashore)((ordbObject)beachRefs[i]).getObject();System.out.println("beach description(map): " + beachx.description);// Another way is to use the getAttributeValue method of ordbObjectordbObject beacho = (ordbObject)beachRefs[i];System.out.println("beach description(getAttr): " +beacho.getAttributeValue("description") );}<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 74Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


Now we will use automatic custom mappingseashores.setAutoPerformCustomMapping(true);Object [] beaches = (Object [])seashores.getArray();// custom mapping was performed automatically// get the beach description using the jseashore instancefor (int i=0; i < beaches.length; i++) {jseashore beach = (jseashore)beaches[i];System.out.println("beach description(map): " +((jseashore)beaches[i]).description );} // Now clean up <strong>Cincom</strong> ORDB workspace used by the collection if(seashores != null) seashores.free(); stmt.close();conn.close(); }}Freeing <strong>Cincom</strong> ORDB workspace storage used byordbCollectionsAn instance of ordbCollection holds a reference to a <strong>Cincom</strong> ORDB collectionthat is maintained in the ORDB client workspace. When your application isfinished using the ordbCollection, you should invoke the free() method on theordbCollection. The free() method will release the workspace storageassociated with the ordbCollection object.All of the samples presented above make use of the free() method.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 75Chapter: 4. <strong>Cincom</strong> ORDB ExtensionsSection: Working with <strong>Cincom</strong> ORDB collections


5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesIntroductionThis chapter documents <strong>JDBC</strong> 3.0 interface specific issues that the <strong>JDBC</strong>developer should be aware of.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not implement the following <strong>JDBC</strong> 3.0interfaces:The <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not implement the following <strong>JDBC</strong> 3.0interfaces:BatchUpdateException DriverPropertyInfo RowSetMetaDataCallableStatement ParameterMetaData RowSetReaderConnectionEvent PooledConnection RowSetWriterConnectionEventListener RowSet XAConnectionConnectionPoolDataSource RowSetEvent XADataSourceDataSourceRowSetInternalDataTruncationRowSetListener<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 76Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Introduction


Supported <strong>JDBC</strong> 3.0 interfacesThe following <strong>JDBC</strong> 3.0 interfaces are supported and described in the sectionsfollowing the table below:ArrayBlobClobConnectionDatabaseMetaDataDriverPreparedStatementRefResultSetResultSetMetaDataSQLInputSQLOutputStatementStructArrayThe java.sql.Array interface is fully implemented by the ordbCollection class.The ordbCollection class also provides additional functionality to allow easiermanagement of <strong>Cincom</strong> ORDB collections. Be sure to issue the free method onthe ordbCollection objects when you are finished with them.BlobClobThe following methods of the java.sql.Blob interface are not supported:♦♦♦♦int setBytes(long pos, byte[] bytes) throws SQLException;int setBytes(long pos, byte[] bytes, int offset, int len) throwsSQLException;java.io.OutputStream setBinaryStream(long pos) throws SQLException;void truncate(long len) throws SQLException;The following methods of the java.sql.Clob interface are not supported:♦♦♦♦int setString(long pos, String str) throws SQLException;int setString(long pos, String str, int offset, int len) throws SQLException;java.io.OutputStream setAsciiStream(long pos) throws SQLException;java.io.Writer setCharacterStream(long pos) throws SQLException;<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 77Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


ConnectionThe database does not support stored procedures, therefore none of the formsCallableStatement method are supported:♦♦♦CallableStatement prepareCall(String sql) throws SQLException;CallableStatement prepareCall(String sql, int resultSetType,int resultSetConcurrency) throws SQLException;CallableStatement prepareCall(String sql, int resultSetType, intresultSetConcurrency, int resultSetHoldability) throws SQLException;You can use ordbObject and/or custom mapping to invoke database methods.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver only supports TYPE_FORWARD_ONLY ResultSets,CONCUR_READ_ONLY ResultSet concurrency, and ResultSet holdability ofCLOSE_CURSORS_AT_COMMIT.If any of the parameters in the following methods do not match the abovevalues, the method will fail:♦♦♦♦♦Statement createStatement(int resultSetType,int resultSetConcurrency) throws SQLException;PreparedStatement prepareStatement(String sql, int resultSetType, intresultSetConcurrency) throws SQLException;void setHoldability(int holdability) throws SQLException;(Will fail if holdability is not CLOSE_CURSORS_AT_COMMIT)Statement createStatement(int resultSetType, int resultSetConcurrency,int resultSetHoldability) throws SQLException;PreparedStatement prepareStatement(String sql, int resultSetType,intresultSetConcurrency, int resultSetHoldability) throws SQLException;<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 78Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


The following method of the java.sql.Connection interface are not supported:♦♦♦♦♦♦♦Savepoint setSavepoint() throws SQLException;Savepoint setSavepoint(String name) throws SQLException;void rollback(Savepoint savepoint) throws SQLException;void releaseSavepoint(Savepoint savepoint) throws SQLException;PreparedStatement preparedStatement(String sql, int autoGeneratedKeys)throws SQLException;public PreparedStatement preparedStatement(String sql, intcolumnIndexes[]) throws SQLException;PreparedStatement preparedStatement(String sql, String columnNames[])throws SQLException;DatabaseMetaDataThe java.sql.DatabaseMetaData interface is fully supported.DriverThe java.sql.Driver interface is fully supported.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 79Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


PreparedStatement<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not support streams for column data. Thefollowing methods are not supported:♦♦♦♦void setAsciiStream(int paramaterIndex, java.io.InputStream fin,int length) throws SQLException;void setBinaryStream(int paramaterIndex, java.io.InputStream fin,int length) throws SQLException;void setCharacterStream(int paramaterIndex, java.io.Reader reader,int length) throws SQLException;void setUnicodeStream(int parameterIndex, InputStream x, int length)throws SQLException;<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not support date/time methods that take analternative calendar. The following methods are not supported if the calendarparameter is not the calendar for the current time zone:♦♦♦void setDate(int parameterIndex, java.sql.Date x, Calendar cal) throwsSQLException;void setTime(int parameterIndex, Time x, Calendar cal) throwsSQLException;void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throwsSQLException;<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not support storing of Blob and Clob data incolumns. You can store references to ordbGlo instances by using the setRefmethod. The following methods are not supported:♦♦void setBlob(int paramaterIndex, Blob x) throws SQLException;void setClob(int paramaterIndex, Clob x) throws SQLException;RefThe java.sql.Ref interface does not support the following methods:♦void setObject(Object value) throws SQLException;<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 80Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


ResultSet<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver only supports ResultSets that areTYPE_FORWARD_ONLY cursors, and CONCUR_READ_ONLY concurrency, andCLOSE_AFTER_COMMIT_holdability. The following java.sql.ResultSet methodsare not supported:♦ boolean absolute(int row) throws SQLException;♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦void afterLast() throws SQLException;void beforeFirst() throws SQLException;void cancelRowUpdates() throws SQLException;void deleteRow() throws SQLException;boolean first() throws SQLException;int getRow() throws SQLException;void insertRow() throws SQLException;boolean isAfterLast() throws SQLException;boolean isBeforeFirst() throws SQLException;boolean isFirst() throws SQLException;boolean isLast() throws SQLException;boolean last() throws SQLException;void moveToCurrentRow() throws SQLException;void moveToInsertRow() throws SQLException;boolean previous() throws SQLException;void refreshRow() throws SQLException;boolean relative(int rows) throws SQLException;boolean rowDeleted() throws SQLException;boolean rowInserted() throws SQLException;boolean rowUpdated() throws SQLException;void setFetchSize(int rows) throws SQLException;All updateXXX methods.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 81Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not support streams for column data. You canuse the ordbGlo object to access data stored in <strong>Cincom</strong> ORDB Glo classes. Thefollowing methods are not supported:♦♦♦♦♦♦InputStream getAsciiStream(int columnIndex) throws SQLException;InputStream getBinaryStream(int columnIndex) throws SQLException;InputStream getBinaryStream(String columnName) throws SQLException;Reader getCharacterStream(int columnIndex) throws SQLException;Reader getCharacterStream(String columnName) throws SQLException;InputStream getUnicodeStream(int columnIndex) throws SQLException;♦ InputStream getUnicodeStream(String columnName) throws SQLException;The getBigDecimal methods that accept a scale parameter have beendeprecated in favor of the <strong>JDBC</strong> 2.0 methods. The following methods are notsupported:♦♦public BigDecimal getBigDecimal(int columnIndex, int scale) throwsSQLExceptionBigDecimal getBigDecimal(String columnName, int scale) throwsSQLException;<strong>Cincom</strong> ORDB does not support named cursors, the following method is notsupported:♦String getCursorName() throws SQLException;<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 82Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


<strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver does not support date/time methods that take analternative calendar. The following methods are not supported if the calendaris not the same as the current time zone calendar:♦♦♦♦♦♦java.sql.Date getDate(int columnIndex, Calendar cal) throws SQLException;java.sql.Date getDate(String columnName, Calendar cal) throwsSQLException;Time getTime(int columnIndex, Calendar cal) throws SQLException;Time getTime(String columnName, Calendar cal) throws SQLException;Timestamp getTimestamp(int columnIndex, Calendar cal) throwsSQLException;Timestamp getTimestamp(String columnName, Calendar cal) throwsSQLException;ResultSetMetaDataThe java.sql.ResultSetMetaData interface is fully supported.SQLInputThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver only implements the java.sql.SQLInput methodsthat are required to support java custom mapping classes generated by theddltojava tool. The following methods are not supported:♦♦♦♦♦♦java.io.InputStream readAsciiStream() throws SQLException;java.io.InputStream readBinaryStream() throws SQLException;boolean readBoolean() throws SQLException;java.io.Reader readCharacterStream() throws SQLException;Object readObject() throws SQLException;java.net.URL readURL() throws SQLException;<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 83Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


SQLOutputThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver only implements the java.sql.SQLOutputmethods that are required to support java custom mapping classes generatedby the ddltojava tool. The following methods are not supported:♦♦♦♦♦♦♦♦♦void writeAsciiStream(java.io.InputStream in) throws SQLException;void writeBinaryStream(java.io.InputStream in) throws SQLException;void writeBlob(Blob blob) throws SQLException;void writeBoolean(boolean b) throws SQLException;void writeCharacterStream(java.io.Reader r) throws SQLException;void writeClob(Clob clob) throws SQLException;void writeObject(SQLData x) throws SQLException;void writeStruct(Struct x) throws SQLException;void writeURL(java.net.URL x) throws SQLException;StatementThe <strong>Cincom</strong> ORDB Database does not support named cursors. The followingmethod is not supported:♦void setCursorName(String name) throws SQLException;StructThe java.sql.Struct interface is fully supported.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 84Chapter: 5. <strong>Cincom</strong> ORDB <strong>JDBC</strong> NotesSection: Supported <strong>JDBC</strong> 3.0 interfaces


6. Coding tips and troubleshootingIntroductionThis chapter describes how to optimize and troubleshoot a <strong>JDBC</strong> application orapplet, including the following topics:♦ <strong>JDBC</strong> and multi-threading♦♦Performance optimizationLogging <strong>JDBC</strong> calls<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 85Chapter: 6. Coding tips and troubleshootingSection: Introduction


<strong>JDBC</strong> and multi-threadingThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver provides support for programs that use multiplethreads.The following files show a simple multithreaded <strong>Cincom</strong> ORDB <strong>JDBC</strong> applicationand can be found in the %ORDB%\demo\jdbc\samples directory:♦ threadSample.java♦♦sqlExecuteThread.javasqlResultsThread.java<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 86Chapter: 6. Coding tips and troubleshootingSection: <strong>JDBC</strong> and multi-threading


Performance optimizationThe following are performance considerations for your <strong>Cincom</strong> ORDB <strong>JDBC</strong>application:♦ Disable auto-commit mode♦♦♦♦♦The array interfaceAutomatic custom mappingConnection poolingTrapping exceptionsSchema locksDisabling auto-commit modeAuto-commit mode indicates to the database whether to issue a commit afterevery SQL statement, after every <strong>Cincom</strong> ORDB <strong>JDBC</strong> Extension that updates adatabase instance or collection, and after every database method invocation.By default, new connection objects are in auto-commit mode. You can controlthe auto-commit mode for a connection with the setAutoCommit() method ofthe java.sql.Connection interface.You can also control the default auto-commit mode for new connections byusing the setAutoCommitDefault() static method of theordbjava.jdbc.ordbDriver class.Commits are expensive operations, and they cause all ResultSets to discardtheir current position.If auto-commit is disabled (recommended), then the <strong>JDBC</strong> driver groups theconnection’s SQL statements, and other database modifications into atransactions that is terminated by either a commit( ) or rollback( ) statement.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 87Chapter: 6. Coding tips and troubleshootingSection: Performance optimization


Example: Disabling AutoCommit. The following example loads the driver andconnects to the database. Since new connections have auto-commit enabled bydefault, this example shows how to disable auto-commit. In the example, connrepresents the Connection object and stmt represents the Statementobject.// Load the <strong>Cincom</strong> ORDB <strong>JDBC</strong> driverDriverManager.registerDriver(new ordbjava.jdbc.ordbDriver());// Connect to the databaseConnection conn =DriverManager.getConnection ("jdbc:cincomordb:demodb", "public", null);// Let the application control transaction boundariesconn.setAutoCommit (false);// Create a StatementStatement stmt = conn.createStatement ();// Disable auto-commit mode for new connectionsordbjava.jdbc.ordbDriver.setAutoCommitDefault(false);Connection conn2 =DriverManager.getConnection ("jdbc:cincomordb:demodb", "public", null);System.out.println("auto-commit for conn2: " + conn2.getAutoCommit());Using the array interfaceUsing the getResultSet(..) methods of the Array interface can save memoryspace. The reason being that the ResultSet returned will only access a singlecollection element from the database when the ResultSet.next() method iscalled.When the getArray(..) methods are used, the driver must allocate a java arraylarge enough to contain all the elements requested, and then access theelements from the database.In any event, the workspace memory associated with the ordbCollection objectshould be freed by invoking the free() method after you are finished using theordbCollection.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 88Chapter: 6. Coding tips and troubleshootingSection: Performance optimization


Automatic custom mappingWhen you enable automatic custom mapping for ordbObject and/orordbCollection, then all object references that have a custom map defined willgenerate new instances of the custom mapped class.Care should be taken when enabling automatic custom mapping for largecollections of objects, and objects that contain many object references.Connection poolingDatabase connects and disconnects are time-consuming. If your applicationneeds to frequently connect and disconnect from the <strong>Cincom</strong> ORDB databaseusing the same username and password, you should consider using connectionpooling.The <strong>Cincom</strong> ORDB <strong>JDBC</strong> driver can maintain a pool of database connectionsthat are available for new connection requests.When connection pooling is enabled, the Connection.close() method willperform the following steps:1. A rollback will be issued on the database connection.2. All database resources (resultSets, Statements, etc) for the connection willbe released.3. The connection will be added to a pool of available connections.When connection pooling is enabled, the Driver.connect() method will checkthe available connections that matches the database, user, password, andlanguage being requested. If a match is found, then the existing connectionwill be used. If not found, then a new database connection will be established.A daemon process is utilized to perform database disconnects on unusedconnection in the available pool. This will take place on a timer controlled bythe application.Two static methods of ordbDriver are used to control connection pooling.These methods are:♦♦setConnectPoolTimeout(long milliseconds)long getConnectPoolTimeout()<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 89Chapter: 6. Coding tips and troubleshootingSection: Performance optimization


setConnectPoolTimeout(long milliseconds)The setConnectPoolTimeout(long milliseconds) static method of ordbDriver isused to enable, and disable pooling, or to alter the timeout duration forconnections. If zero is passed, all existing connections in the available poolwill be disconnected from the database, and connection pooling will bedisabled. If a non-zero value is specified, then connection pooling will beenabled. The parameter specifies the number of milliseconds that a databaseconnection should remain in the available connection pool before beingdisconnected from the database.long getConnectPoolTimeout()The getConnectPoolTimeout() will return zero if connection pooling is disabled(the default). The connection timeout value in milliseconds will be returned ifconnection pooling is enabled.By default, connection pooling is disabled.If you make use of connection pooling, you should make sure to issue anordbDriver.setConnectPoolTimeout(0) statement when your application exists.Failure to do this will result in spurious (but harmless) errors reported by thedatabase server occurring because of the open connections being terminatedwhen the client process (your application) shuts down.The file poolingSample.java in the %ORDB%\demo\jdbc\samples directorycontains an example that uses connection pooling.Trapping exceptions<strong>JDBC</strong> handles most errors that occur in the program as exceptions. Javaprovides the try...catch statement to catch the exception and theprintStackTrace() method to print the stack trace.The following code fragment illustrates how you can catch SQL exceptions andprint the stack trace:try { }catch(SQLException e){ e.printStackTrace (); }<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 90Chapter: 6. Coding tips and troubleshootingSection: Performance optimization


Schema locksThe default behavior of the <strong>Cincom</strong> ORDB Client API is to maintain schema readlocks across transaction boundaries (controlled by the KEEP_SCHEMA_LOCKSparameter). This can cause unwanted concurrency problems. You can controlwhether or not schema locks are attempted to be held across transactionboundaries by making use of two methods of the ordbConnection class:♦♦commit(boolean releaseSchemaLocks)rollback(boolean releaseSchemaLocks)For more information on the ordbConnection class methods, refer to thejavadoc located in your %ORDB%\docs\jdbc\ordbjava directory.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 91Chapter: 6. Coding tips and troubleshootingSection: Performance optimization


Logging <strong>JDBC</strong> callsThe <strong>Cincom</strong> ORDB <strong>JDBC</strong> Driver can produce log records that may aid yourdebugging efforts. The log can be enabled for the entire application, or for asingle connection.♦To produce log records for <strong>JDBC</strong> calls, set the “logging” property to“<strong>JDBC</strong>”.♦ To produce a more detailed log, set the “logging” property to “ALL”.The log output will be written to the location specified by the setLogWriter()method of java.sql.DriverManager. Log records will be written to standardoutput if no log writer has been established with the setLogWriter() method.Example: Turning on all logging. The following example turns on all loggingfor a connection:java.util.Properties info = new java.util.Properties();info.put ("user", "public");info.put ("password", NULL);info.put ("logging", "ALL");getConnection ("jdbc:cincomordb:demodb",info);Example: Enabling logging at application start-up. The following exampleenables logging at application start-up time; prefix the “logging” with“ordbjava.jdbc.” on your java command:java –Dordbjava.jdbc.logging=ALL <strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 92Chapter: 6. Coding tips and troubleshootingSection: Logging <strong>JDBC</strong> calls


A. <strong>JDBC</strong> SamplesPrerequisitesMost of the samples presented in this manual are installed both in source andbyte code in your installation.In order to run the samples from your installation, you need:♦♦A working Java Developer Kit 1.4 or higher installed on your machine.Access to a running demodb database (or other database with the demodbschema and data loaded).<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 93Appendix: A. <strong>JDBC</strong> SamplesSection: Prerequisites


Accessing <strong>JDBC</strong> samplesUse one of the following commands to invoke the samples:♦♦On NT:java -cp%ORDB%\ordbjava.jar;%ORDB%\demo.jdbc.samples.[]On UNIX:java -cp$ORDB/ordbjava.jar;$ORDB/demo.jdbc.samples.[]where:- is the name of the sample you want to run- is the name of the database that contains the demodbschema and data is only needed if the database name is not demodb.<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 94Appendix: A. <strong>JDBC</strong> SamplesSection: Accessing <strong>JDBC</strong> samples


Sample programsThe %ORDB%\demo\jdbc\samples directory contains sample programs for the<strong>Cincom</strong> ORDB <strong>JDBC</strong> driver. The following are the valid sample files:♦ collectionSample1♦ collectionSample2♦ collectionSample3♦ collectionSample4♦ collectionSample5♦ customMappingSample1♦ customMappingSample2♦ driverVersion♦ getAttributeSample♦ jdbcHelloWorld♦ methodSample♦ ordbObjectSample♦ poolingSample♦ preparedStmtSample♦ querySample♦ threadSample<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 95Appendix: A. <strong>JDBC</strong> SamplesSection: Sample programs


IndexAaccesing attribute values,example 31accessing attribute values 31architecture of <strong>JDBC</strong> drivers 9arrays, retrieving elements 62attribute values, accessing 31auto-commit mode, disabling87CCINCOM ORDBcollections 61creating and modifying 69custom mapping 73heterogeneous 65retrieving 62database, error messages 27extensions, in general 28<strong>JDBC</strong> extensions 28objects, creating Javaclasses for 38class jaccommodations.javaexample 44class jresort.java example 40coding tips 85collections, CINCOM ORDBcreating and modifying 69custom mapping 73heterogeneous 65retrieving 62collections, TOTAL XML 61connection to databaseclosing 23example 24opening 21custom mappingcollections 73controlling 50inserting, deleting, updating55writing classes 58Ddatabase names for Javaclasses 39databasesclass names, relating Javaclasses to 48connectionclosing 23creating code for 20example 24opening 21testing 15inserting, deleting, updating33invoking methods 36schema, generating Javaclasses from 39datatype mappings 25ddltojava utilitydescribed 39syntax 39directories, checking 13displaying error messages 27driversarchitecture 9requirements 9verifying installation 12Eerror messagesdisplaying 27returning 27examplesaccessing attribute values 31collections and custommapping 73connecting to database 24creating and modifyingcollections 70deleting database instances33disabling AutoCommit 88getAttributes method 52getDriverVersion() method14heterogeneous collectionmethods 65homogeneous collections 67inserting database instances33<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 96Index


invoking database methods36jaccommodations.java 44Java primitive arrays 67java.sql.ResultSet.getObjectmethod 50jdbcHelloWorld.javaprogram 16jresort.java 40logging at application startup92logging for a connection 92ordbObject.getObjectmethod 51retrieving subset of arrayelement 63updating database instances33extensions, <strong>Cincom</strong> ORDBin general 28Ffiles, checking 13Ggenerating Java classes, fromDB schema 39getDriverVersion() methodexample 14getMessage method 27Iinstallation, verifying driver12Jjaccommodations.javaexample 44Javaclassescreating custom 38database names 39generating from DBschema 39relating to DB class names48samples 40native datatype mappings 25<strong>JDBC</strong>basic features 19checking directories 13datatype mappings 25definition 8determining version 14driversarchitecture 9error messages 27registering 20requirements 9specific information 20verifying installation 12logging calls 92multi-threading 86overview 8testing connection 15jdbcHelloWorld.java programexample 16jresort.java, example 40Mmapping, customcollections 73controlling 50inserting, deleting, updating55writing classes 58Oobjects, working with 31optimizing performance 87ordbjava.jdbc package,classes 28Pperformance, optimizing 87printStackTrace method 27Qquery, executing 22<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 97Index


RResultSet objectclosing 23processing 23returning 22returning error messages 27Ttroubleshooting 85Vvariables, checking 14SSQLdata interface 58datatype mappings 25Statement objectclosing 23creating 21<strong>JDBC</strong> <strong>Developer's</strong> <strong>Guide</strong>, P25-9504-03 Page 98Index

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!