0% found this document useful (0 votes)
47 views

SL330 - Database Application Programming With Java - Oh - 1099

This document provides an overview of a course on database application programming with Java technology. The course teaches how to use JDBC and object-oriented analysis and design principles to develop multi-tier database applications. It outlines the course objectives, modules, and topics covered in each module.

Uploaded by

Jackie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

SL330 - Database Application Programming With Java - Oh - 1099

This document provides an overview of a course on database application programming with Java technology. The course teaches how to use JDBC and object-oriented analysis and design principles to develop multi-tier database applications. It outlines the course objectives, modules, and topics covered in each module.

Uploaded by

Jackie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 239

Sun Educational Services

Database Application Programming


With Java Technology

SL-330

Database Application Programming With Java Technology October 1999


Sun Educational Services

Copyright 1999 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document may
be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other countries, exclusively
licensed through X/Open Company, Ltd.

Sun, Sun Microsystems, the Sun Logo, Java, JDBC, Java Naming and Directory Interface, and JavaBeans are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S.
and other countries.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trade-
marks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching
and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which
license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements.

U.S. Government approval required when exporting the product.

RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g) (2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015
(b)(6/95) and DFAR 227.7202-3(a).

DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE
HELD TO BE LEGALLY INVALID.

Database Application Programming With Java Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Preface

About This Course

Database Application Programming With Java Technology October 1999


Sun Educational Services

Course Goal
This course provides you with knowledge and skills to:

• Use Java™ technology and the JDBC™ application


programming interface (API) to develop multi-tier
database applications

• Use the appropriate application and database


architecture for your database applications

Database Application Programming With Java Technology Preface, slide 2 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Course Overview
• Retrieving and manipulating database data using the
JDBC API
• JDBC 1.0 and 2.0 features
• Application design for a database application
• Mapping database tables to object models
• SQLJ

Database Application Programming With Java Technology Preface, slide 3 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services
Course Map
Database Application Programming With Java Technology Preface, slide 4 of 16
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

Module-by-Module Overview
• Module 1 – “JDBC Overview”
• Module 2 – “Using JDBC”
• Module 3 – “OOAD and Database Design”
• Module 4 – “JDBC Advanced Topics”
• Module 5 – “JDBC 2.0 Core Features”
• Module 6 – “JDBC 2.0 Standard Extensions”
• Module 7 – “Row Set Implementation”
• Module 8 – “JDBC and Application Architecture”

Database Application Programming With Java Technology Preface, slide 5 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Module-by-Module Overview
• Appendix A – “Database Basics”
• Appendix B – “Using SQLJ”

Database Application Programming With Java Technology Preface, slide 6 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Course Objectives
• Design a multi-tier database application architecture
• Create a multi-tier database application using the Java
programming language and the JDBC 1.0 API
• Map an object-oriented design to a relational database
• Explain the features added to the JDBC 2.0 API

Database Application Programming With Java Technology Preface, slide 7 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Skills Gained by Module


Module

Skills Gained 1 2 3 4 5 6 7 8
Design a multi-tier database application architecture
Create a multi-tier database application using the Java
programming language and the JDBC 1.0 API
Map an object-oriented design to a relational database
Explain the features added to the JDBC 2.0 API

Database Application Programming With Java Technology Preface, slide 8 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Guidelines for Module Pacing

Module Day 1 Day 2 Day 3 Day 4


About This Course A.M.
JDBC Overview A.M.
Using JDBC P.M.
OOAD and Database Design A.M.
JDBC Advanced Topics P.M.
JDBC 2.0 Core Features A.M.
JDBC 2.0 Standard Extensions P.M.
Row Set Implementation A.M.
JDBC and Application P.M.
Architecture

Database Application Programming With Java Technology Preface, slide 9 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Topics Not Covered


• Object-oriented theory
• Java programming language basics
• Relational database design and structured query
language (SQL) basics

Database Application Programming With Java Technology Preface, slide 10 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

How Prepared Are You?


• Design applications using object-oriented analysis and
design
• Develop applications using the Java programming
language
• Use basic SQL to retrieve and manipulate data in a
relational database

Database Application Programming With Java Technology Preface, slide 11 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Introductions
• Name
• Company affiliation
• Title, function, and job responsibility
• Java programming language experience
• SQL experience
• Relational database experience
• Reasons for enrolling in this course
• Expectations for this course

Database Application Programming With Java Technology Preface, slide 12 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

How to Use Course Materials


• Objectives
• Relevance
• Overhead image
• Lecture
• Exercise
• Check Your Progress
• Think Beyond

Database Application Programming With Java Technology Preface, slide 13 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Icons

Additional resources

Demonstration

Discussion

Database Application Programming With Java Technology Preface, slide 14 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Typographical Conventions
• Courier is used for the names of commands, files, and
directories, as well as on-screen computer output.

• Courier bold is used for characters and numbers that


you type.

• Courier italic is used for variables and command-


line placeholders that are replaced with a real name or
value.

• Palatino italics is used for book titles, new words or


terms, or words that are emphasized.

Database Application Programming With Java Technology Preface, slide 15 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Syntax Conventions
• Syntax and example
type varIdentifier

int myFirstVariable;

• Italicized variables
class className

• Square brackets for optional elements


[classModifier] class name {block}

Database Application Programming With Java Technology Preface, slide 16 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Module 1

JDBC Overview

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 1, slide 2 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

What Is the JDBC API?


• The JDBC API is:
• A standard data access interface to a wide range of
relational databases
• A set of classes and interfaces that are part of the
Java programming language
• JDBC enables:
• Connecting to a database
• Sending a String SQL query to the database
• Processing the results

Database Application Programming With Java Technology Module 1, slide 3 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

What Is the JDBC API?


• The JDBC API has two main parts.
• Java application developers’ interface for Java
programming language developers
• JDBC driver developers’ implementation interface
• This course concentrates on the developer interface.

Database Application Programming With Java Technology Module 1, slide 4 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Drivers
• Are a collection of classes implementing JDBC classes
and interfaces
• Provide a class that has implemented the
java.sql.Driver interface

Database Application Programming With Java Technology Module 1, slide 5 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Drivers
Java application
(JDBC API)

JDBC driver manager

URL URL URL URL

JDBC-NET JDBC-ODBC Driver A Driver B


driver Bridge driver

ODBC and
DB drivers

Database Application Programming With Java Technology Module 1, slide 6 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Drivers
Category Driver Category Description Pure Java Net
Technology Protocol
1 JDBC-ODBC Allows ODBC drivers to be used as No Direct
Bridge JDBC drivers; was implemented to
get the JDBC API working quickly
2 Native API based Built on top of a native database No Direct
client library; translates the JDBC
calls into calls to the API of the
database client library
3 JDBC-Net Communicates with an Yes Connector
intermediary server seated
between the client and the
database, using a network protocol
that is specific to the intermediary
4 Native Protocol Translates JDBC calls directly into Yes Direct
the network protocol used by the
DBMS, allowing direct calls from
the client to the database

Database Application Programming With Java Technology Module 1, slide 7 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

JDBC/ODBC Bridge Plus ODBC


Driver
• Uses existing technology
• Provides JDBC access to the database using an existing
ODBC driver.
• Requires code to be installed on each client.
• Is most appropriate with fewer client installations
• Has several potential failure points

Database Application Programming With Java Technology Module 1, slide 8 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

JDBC/ODBC Bridge Plus ODBC


Driver
Application
Database

JDBC API

ODBC bridge ODBC driver

Client Server

Database Application Programming With Java Technology Module 1, slide 9 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Native API
• This type is built on top of a native database client
library.
• The driver translates the JDBC calls into calls to the API
of the database client library.
• The library is distributed by the provider of the
database management system (DBMS).
• It does not accomplish the goal of the JDBC API, which
is to write once and run anywhere.

Database Application Programming With Java Technology Module 1, slide 10 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Native API

Application

JDBC API

Native code
libraries Database

Client Server

Database Application Programming With Java Technology Module 1, slide 11 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

JDBC-Net
• This type communicates with an intermediary server
seated between the client and the database.
• It uses a network protocol specific to the intermediary.
• No native code needs to be installed on the database
client machines.
• It has the most flexibility.

Database Application Programming With Java Technology Module 1, slide 12 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

JDBC-Net

Application

JDBC API
DBMS-specific
JDBC-Net translator Database

Client Intermediary server Server

Database Application Programming With Java Technology Module 1, slide 13 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Native Protocol
• Translates JDBC calls directly into the network
protocol used by the DBMS
• Allows direct calls from the client to the database
• Has good performance, but no flexibility for switching
DBMSs

Database Application Programming With Java Technology Module 1, slide 14 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Native Protocol

Application

JDBC API

Native protocol Database

Client Server

Database Application Programming With Java Technology Module 1, slide 15 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Finding Drivers
http://java.sun.com/products/jdbc/drivers.html

Database Application Programming With Java Technology Module 1, slide 16 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

JDBC Developer Interface


The JDBC API developer interface is defined in two packages.
• java.sql – Primary features of JDBC in Java 2
Platform, Standard Edition
• javax.sql – Extended functionality in Java 2 Platform,
Enterprise Edition

Database Application Programming With Java Technology Module 1, slide 17 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Classes and Interfaces


• DriverManager – Manages database drivers and
supports new database connection creation
• Driver – Represents a specific JDBC implementation
• Connection – Is a session with the specific database
• Statement, PreparedStatement,
CallableStatement – Are containers for executing a
SQL statement on a connection
• ResultSet – Provides access to a table of data

Database Application Programming With Java Technology Module 1, slide 18 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
JDBC Developer Interface
java.lang.Object
Array*
java.lang.Throwable
Blob*
java.lang.Exception
Clob*
SQLException
Struct*
BatchUpdateException
SQLData*
SQLWarning
DataTruncation
SQLInput*
Connection
SQLOutput*
DatabaseMetaData
Driver
DriverManager java.util.Date
DriverPropertyInfo Date
Ref* Time
ResultSet TimeStamp
ResultSetMetaData Legend
Statement Class
Abstract
Class
PreparedStatement
Interface
Extends
CallableStatement
Types * New with JDBC 2.0
Database Application Programming With Java Technology Module 1, slide 19 of 29
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Identifying a Database Using a URL


A JDBC uniform resource locator (URL):
• Identifies a database so the correct driver can recognize
and establish a connection with it.
• Is determined by vendor
• Contains encoded information
• Allows for a level of indirection

Database Application Programming With Java Technology Module 1, slide 20 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Basic URL Syntax


• Full URL syntax
jdbc:subprotocol:subname

• Example
jdbc:odbc:wombat

Database Application Programming With Java Technology Module 1, slide 21 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

jdbc
• Always jdbc

Database Application Programming With Java Technology Module 1, slide 22 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

subprotocol
• Is the name of the driver or the type of database
connectivity mechanism
• Is often odbc
• Can be the network naming service

Database Application Programming With Java Technology Module 1, slide 23 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Using a Network Naming Service as


the Subprotocol
• Basic syntax
jdbc:naming_service:data_source_name

• Example
jdbc:dcenaming:accounts-payable

Database Application Programming With Java Technology Module 1, slide 24 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

odbc Subprotocol
• Basic syntax
jdbc:odbc:dataSrcName[;attributeName=attributeValue]

• Example
jdbc:odbc:fred
jdbc:odbc:wombat
jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER
jdbc:odbc:qeora;UID=kgh;PWD=fooey

Database Application Programming With Java Technology Module 1, slide 25 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

subname
• Identifies the database
• Can have a subsubname

Database Application Programming With Java Technology Module 1, slide 26 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Connecting to a Remote Server


A database on a remote server needs a URL with more
information.
• Syntax
jdbc:subprotocol://hostname:port/subsubname

• Example
jdbc:dbnet://wombat:3560/fred

Database Application Programming With Java Technology Module 1, slide 27 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Describe the purpose of the JDBC API
• Explain how to use the JDBC API to connect a Java
application to a database
• Define the different components of the JDBC
architecture
• Select the correct kind of JDBC driver for a given
application architecture
• Describe the URL syntax used to identify a database

Database Application Programming With Java Technology Module 1, slide 28 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Think Beyond
From what you now know of the JDBC API, list the steps that
would be necessary to connect to and retrieve data from a
database.

Database Application Programming With Java Technology Module 1, slide 29 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module 2

Using JDBC

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 2, slide 2 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Creating a Basic JDBC Application


• Step 1 – Register a driver
• Step 2 – Establish a connection to the database
• Step 3 – Create a statement
• Step 4 – Execute the SQL
• Step 5 – Process the results
• Step 6 – Close down JDBC objects

Database Application Programming With Java Technology Module 2, slide 3 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Creating a Basic JDBC
Application
// Step 1
1 Class.forName("oracle.jdbc.driver.OracleDriver");
// Step 2
2 Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts",
"marcl", "mpuppet");
// Step 3
3 Statement stmt = con.createStatement();
// Step 4
4 String SQL_stmt = "SELECT a, b, c FROM table1";
5 ResultSet rs = stmt.executeQuery(SQL_stmt);
// Step 5
6 while (rs.next()) {
7 System.out.println("a=" + rs.getInt("a"));
8 System.out.println("b=" + rs.getString("b"));
9 System.out.println("c=" + rs.getFloat("c"));
10}
// Step 6
11 rs.close();
12 stmt.close();
13 con.close();
Database Application Programming With Java Technology Module 2, slide 4 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 1 – Registering a Driver


• The driver is used to connect to the database.
• The JDBC API uses the first driver it finds that can
successfully connect to the given URL.
• You can load multiple drivers at the same time.
• Register a driver:
• Using the Class loader
• Instantiating a driver
• Using the jdbc.drivers property

Database Application Programming With Java Technology Module 2, slide 5 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Using the Class Loader


To communicate with a database engine using the JDBC API,
create an instance of the JDBC driver.
• Syntax
Class.forName(driverName);

• Example
Class.forName("oracle.jdbc.driver.OracleDriver");

Database Application Programming With Java Technology Module 2, slide 6 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Instantiating a Driver
If you need an explicit reference to the Driver object, use the
new keyword.
• Syntax
Driver drvRefVar = new DriverConstructor;

• Example
Driver drv = new oracle.jdbc.driver.OracleDriver();

Database Application Programming With Java Technology Module 2, slide 7 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Defining the jdbc.drivers Property


Define the jdbc.drivers property as a list of driver class
names.
• Syntax
jdbc.drivers=driverName[:driverName]

• Example
jdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver

Database Application Programming With Java Technology Module 2, slide 8 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Using the -D Option With the java


Command
To use this method, specify the name=value pair.
• Syntax
java -Djdbc.drivers=driverName[:driverName]

• Example
java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver

Database Application Programming With Java Technology Module 2, slide 9 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Choosing the Best Registration


Approach
For each approach, what are the advantages and
disadvantages, and why?

Database Application Programming With Java Technology Module 2, slide 10 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 2 – Establishing a Connection to


the Database
1. DriverManager calls getConnection(urlString),
which calls Driver.connect(urlString).
2. The URL is parsed.
3. When a driver responds positively to the database
URL, the DriverManager makes a connection.
4. If the driver does not match, null is returned and
the next driver in the vector is checked.
5. If a connection is not made, a SQLException is
thrown.

Database Application Programming With Java Technology Module 2, slide 11 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Connection Process
getConnection(urlString)
DriverManager
Application

connect(urlString)

Connection
null null

jdbc:A jdbc:B jdbc:odbc


driver driver driver

Successful
connection

accounts

Database Application Programming With Java Technology Module 2, slide 12 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

DriverManager.getConnection
• Methods
getConnection (urlString)
getConnection (urlString, PropertiesObject)
getConnection (urlString, user, password)

• Syntax
Connection conRefVar = DriverManager.getConnection(arguments);

• Example
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts");

Database Application Programming With Java Technology Module 2, slide 13 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Driver.Connect
• Makes a direct call to a specific Driver object.
• Avoids the problems of standard approach.

Database Application Programming With Java Technology Module 2, slide 14 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Driver.Connect
• Syntax
Connection conRefVar = Driver.connect(urlString, PropertiesInfo);

• Example
1 Driver drv = new oracle.jdbc.driver.OracleDriver();
2 Connection con = null;
3 try{
4 // Pass the connection request directly to THIS driver.
5 // If the connection attempt fails, the application
6 // will NOT try to connect to any other JDBC drivers.
7 con = drv.connect("jdbc:oracle:thin:@java1.com:1521:accounts",
null);
8 }
9 catch (SQLException exc){
10 // If unable to obtain a connection, take some kind
11 // of recovery action here. Options might include
12 // connecting to an alternate DB, prompting the user
13 // for action, or exiting the application.
14}

Database Application Programming With Java Technology Module 2, slide 15 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 3 – Creating a Statement


• Statement
• PreparedStatement
• CallableStatement

Database Application Programming With Java Technology Module 2, slide 16 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
Get a Statement object from the
Connection.createStatement method.

Database Application Programming With Java Technology Module 2, slide 17 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
• Syntax
Statement stmtRefVar = conRefVar.createStatement();

• Examples
1 Statement stmt;
2 try {
3 stmt = con.createStatement();
4 } catch (SQLException e) {
5 System.out.println (e.getMessage());
6 }
7 ResultSet rs = stmt.executeQuery
("SELECT * FROM customer WHERE ID = ’11’");

Database Application Programming With Java Technology Module 2, slide 18 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

PreparedStatement
• A precompiled SQL statement that is more efficient
than repeatedly calling the same SQL statement.
• Extends Statement.

Database Application Programming With Java Technology Module 2, slide 19 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

PreparedStatement
• Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement(sqlString);

• Examples
1 public boolean prepStatement(float sales, String name){
2 PreparedStatement prepStmnt = con.prepareStatement
("SELECT * FROM coffees WHERE cof_name = ?");
3 prepStmnt.setString(1, "Espresso");
4 ResultSet rs = prepStmnt.executeQuery();
5 }

1 PreparedStatement ps = c.prepareStatement(
"UPDATE customer SET order_num = ? WHERE cid = ?");
2 ps.setInt(1, 543);
3 ps.setString(2, "0147");
4 int result = ps.executeUpdate();

Database Application Programming With Java Technology Module 2, slide 20 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

CallableStatement
• Lets you execute non-SQL statements against the
database.
• Extends PreparedStatement.

Database Application Programming With Java Technology Module 2, slide 21 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

CallableStatement
• Syntax
CallableStatement cstmtRefVar = conRefVar.prepareCall(sqlString);

• Examples
1 String coffeeName= "Espresso";
2 CallableStatement querySales = con.prepareCall("{call return_sales[?, ?]}");
3 try {
4 querySales.setString(1, coffeeName);
5 querySales.registerOutParameter(2, Type.REAL);
6 querySales.execute();
7 float sales = querySales.getFloat(2);
8 } catch (SQLException e){
9 System.out.println("Query failed");
10 e.printStackTrace();
11}

1 CallableStatement cs = c.prepareCall ("{call get_order_number [?, ?]}");


2 cs.setString(1, "0147");
3 cs.registerOutParameter(2, Type.INTEGER);
4 cs.execute();
5 int returnVal = cs.getInt(2);

Database Application Programming With Java Technology Module 2, slide 22 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Comparing Statement Interfaces


Statement PreparedStatement CallableStatement
Where is code Client Client Server
created?
Where is code Client Server Server
stored?
Technologies for Java programming Java programming The procedural
writing code language, SQL language, SQL language for the
operations operations database on the target
platform, such as
PLSQL (the procedural
language for SQL)
Configurability High High the first time, Low
then low
Portability High High, provided the Low
database supports
PreparedStatement
Efficiency for Low Low the first time, then High
transferring data high

Database Application Programming With Java Technology Module 2, slide 23 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 4 – Executing the SQL


• SQL statement is passed unaltered to the underlying
database connection.
• The result is a table of data accessible through
java.sql.ResultSet.
• The statement is coupled with the corresponding
ResultSet.

Database Application Programming With Java Technology Module 2, slide 24 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
• executeQuery(sqlString)
• executeUpdate(sqlString)
• execute(sqlString)

Database Application Programming With Java Technology Module 2, slide 25 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
Statement.executeQuery:
• Syntax
1 Connection conRefVar = DriverManager.getConnection(urlString);
2 Statement stmtRefVar = conRefVar.createStatement();
3 ResultSet resultsetRefVar = stmtRefVar.executeQuery (sqlString);

• Example
1 Connection con = DriverManager.getConnection("jdbc:odbc:accounts");
2 Statement stmt = con.createStatement();
3 ResultSet rs = stmt.executeQuery("SELECT * from employees");

Database Application Programming With Java Technology Module 2, slide 26 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 5 – Processing the Results


• To retrieve data from the ResultSet object, use its
assessor methods.
• Retrieve these values using a column name or index.
• A ResultSet:
• Keeps a cursor pointed to current row
• Is initially positioned before its first row

Database Application Programming With Java Technology Module 2, slide 27 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 5 – Processing the Results


• Syntax
1 while (resultsetRefVar.next()) {
2 System.out.println ("column: " +
resultsetRefVar.getXXXMethod(column));
3 }

• Example
1 while (rs.next()) {
2 System.out.println();
3 System.out.println("Coffee Name: " + rs.getString(1));
4 System.out.println("Supplier ID: " + rs.getInt(2));
5 System.out.println("Price : " + rs.getFloat(3));
6 System.out.println("Sales : " + rs.getInt(4));
7 }

Database Application Programming With Java Technology Module 2, slide 28 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Step 6 – Closing Down JDBC Objects


Close down the following:
• Connection
• Statement
• ResultSet
1 try {
2 rs.close();
3 stmt.close();
4 con.close();
5 }
6 catch (SQLException ex) {
7 ex.printStackTrace();
8 }

Database Application Programming With Java Technology Module 2, slide 29 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Exercise: Using JDBC


• Objectives
• Tasks
• Summary

Database Application Programming With Java Technology Module 2, slide 30 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Select an appropriate method to register a JDBC driver
• Establish a database connection with the registered
JDBC driver
• Query a database using the JDBC connection
• Select the appropriate type of statement given the data
query requirements
• Manipulate data in the database using a JDBC
connection

Database Application Programming With Java Technology Module 2, slide 31 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Process the results of a query
• Shut down the appropriate objects after a JDBC process
is complete

Database Application Programming With Java Technology Module 2, slide 32 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Think Beyond
• The Java programming language is object oriented; a
relational database is not.
• What do you need to do to connect the Java technology
object model logically to the database?

Database Application Programming With Java Technology Module 2, slide 33 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module 3

OOAD and Database Design

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 3, slide 2 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module Overview
• During object-oriented application development, you
need to determine:
• How to uniquely identify each row
• How tables relate to the objects
• How tables relate to each other

Database Application Programming With Java Technology Module 3, slide 3 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Object ID Overview
• Every row in a table must be uniquely identifiable.
• In databases, this is represented at the table level by a
primary key.
• Object IDs (OIDs) can more reliably identify records
uniquely.

Database Application Programming With Java Technology Module 3, slide 4 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Object IDs and Primary Keys


OIDs:
• Transcend individual tables.
• Can transcend databases
• Simplify mapping of an object to tables
• Can more easily be unique
• Do not have unnecessary ties to business meaning

Database Application Programming With Java Technology Module 3, slide 5 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Object IDs and Primary Keys


You can make an OID unique:
• Within a class
• Within a class hierarchy
• Across all classes

Database Application Programming With Java Technology Module 3, slide 6 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Single-row Table
• Use a single-row table that stores the next available
unique OID.
• Each time the value is used and assigned to a new
object, the value in the table is incremented.
• Concurrency issues cause a performance bottleneck
when objects are created.

Database Application Programming With Java Technology Module 3, slide 7 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

High/Low
• The OID has a high and a low value.
• The high value is:
• Stored in a single-row table
• Retrieved at the beginning of the session
• The low value is:
• Assigned and incremented by the application
• Appended to the high value

Database Application Programming With Java Technology Module 3, slide 8 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
High/Low
High Value
1 User A
5000
High Value
2 User A
5000 5001
5000
High Value
3 User B
5001
High Value
4 User B
5001 5002
5001
User A
5000
OID CustID FirstName LastName SSN
5
50001 C239PPL Joe Mays 674-58-4013
User B
5001
OID CustID FirstName LastName SSN
6
50011 C244SOL Kara Stelter 101-12-0086
50012 C249FGW Mike Grom 503-50-9901
Database Application Programming With Java Technology Module 3, slide 9 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Object-Relational Mapping
• In an object-oriented model, data is stored as attributes.
• In a relational database, data is stored in rows.
• The class model must be mapped to the relational
model.
• Inheritance complicates mapping.

Database Application Programming With Java Technology Module 3, slide 10 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Object-Relational Mapping
Complete these steps to map the class model to the database
model.
• Map classes to tables
• Map attributes to columns
• Map class relationships to tables

Database Application Programming With Java Technology Module 3, slide 11 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Mapping Classes to Tables


Approaches to mapping class inheritance to a relational
database:
• One table for each class
• One table for each concrete class
• One table for an entire class hierarchy

Database Application Programming With Java Technology Module 3, slide 12 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
One Table for Every Class
Classes
abstractPerson
personOID
firstName
lastName
address
Customer Employee
customerOID employeeOID
salutation SSN
Tables
Person
personOID firstName lastName address
Customer Employee
customerOID salutation personOID employeeOID SSN personOID
Database Application Programming With Java Technology Module 3, slide 13 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One Table for Every Class


• Advantages:
• This approach most closely conforms to object-
oriented concepts.
• It supports polymorphism.
• Maintenance is easy because there is no duplication.
• Disadvantages:
• There are many tables to maintain.
• It takes longer to read and write to the tables.
• Reporting directly from tables is difficult.

Database Application Programming With Java Technology Module 3, slide 14 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
One Table for Each
Concrete Class
Classes
abstractPerson
firstName
lastName
address
Customer Employee
customerOID employeeID
salutation SSN
Tables
Customer
firstName lastName address customerOID salutation
Employee
firstName lastName address employeeOID SSN
Database Application Programming With Java Technology Module 3, slide 15 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One Table for Each Concrete Class


• Advantages:
• Reporting directly from tables is easy.
• Disadvantages:
• If you modify a class, you must modify its table and
the table for any subclasses.
• Data definitions are duplicated.

Database Application Programming With Java Technology Module 3, slide 16 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
One Table for an Entire
Class Hierarchy
Classes
abstractPerson
firstName
lastName
address
personOID
Customer Employee
salutation SSN
Table
Person
firstName lastName address personOID salutation SSN
Database Application Programming With Java Technology Module 3, slide 17 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One Table for an Entire Class Hierarchy


• Advantages:
• Model is easy to understand.
• Polymorphism is supported.
• Reporting directly from tables is easy.

Database Application Programming With Java Technology Module 3, slide 18 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One Table for an Entire Class Hierarchy


Disadvantages:
• Database table must be changed with each addition.
• Database tables can become extremely large.
• It is difficult to enforce rules on the database.
• Each time you add a new attribute, the database table
requires a change.
• When you add a new column, you might need to
update all records with a value for that column.
• Routine maintenance takes more time.

Database Application Programming With Java Technology Module 3, slide 19 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Mapping Two Classes to
One Table
Classes
Address PostalCode
addressOID addressOID
line1 postcodeOID
line2 postalCode
city
state
Table
addressOID line1 line2 city state postcodeOID postalCode
Database Application Programming With Java Technology Module 3, slide 20 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Mapping Two Classes to One Table


Example:
• An Address class has a postal code.
• You could make the postal code a class of its own, to
verify it.
• When mapping to the relational table, combine the
Address and Postal Code classes into one table.

Database Application Programming With Java Technology Module 3, slide 21 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Mapping Class Attributes
to Table Columns
SQL Type Java Technology Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Database Application Programming With Java Technology Module 3, slide 22 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Mapping Class Relationships to Tables


• Table relationships are maintained through foreign
keys.
• A foreign key for one table is a primary key for another
table.
• For one-to-one or one-to-many relationships, use a
primary key in one table and a foreign key in the other.
• When the OID is the primary key, it becomes a foreign
key in the related table.

Database Application Programming With Java Technology Module 3, slide 23 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
One-to-One Relationships
Classes
Car Engine
1 1
carOID engOID
engOID carOID
year model
model cylinders
doors serNum
Tables
Car
carOID engOID year model doors
Engine
engOID carOID model cylinders serNum
Database Application Programming With Java Technology Module 3, slide 24 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One-to-One Relationships
• A Car class and an Engine class, each with its own
table, have a one-to-one relationship.
• The Car OID would be in the Engine table as a foreign
key, or the Engine OID would be in the Car table as a
foreign key.

Database Application Programming With Java Technology Module 3, slide 25 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
One-to-Many
Relationships
Classes
Order OrderLine
1 *
orderOID OLOID
isPrePaid orderOID
number quantity
dateReceived price
orderlines[ ]
Tables
Order
orderOID isPrePaid number dateReceived
OrderLine
OLOID orderOID quantity price
Database Application Programming With Java Technology Module 3, slide 26 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

One-to-Many Relationships
• The OID of the first class (with one record) is added to
the table of the second class (with many records).
• In an order entry program, one order has many line
items.
• orderOID is added to the OrderLine table.

Database Application Programming With Java Technology Module 3, slide 27 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Many-to-Many
Relationships
Classes
Address Customer
* *
addrOID custOID
line1 name
line2 address [ ]
city
state
postalCode
Tables
Address
addrOID line1 line2 city state postalCode
Customer CustomerAddress table (join table)
custOID name addrOID custOID
Database Application Programming With Java Technology Module 3, slide 28 of 33
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Many-to-Many Relationships
• Address to Customer is a many-to-many relationship.
• You could create a join table containing customerOID
and addressOID.

Database Application Programming With Java Technology Module 3, slide 29 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Many-to-Many Relationships
Address table Join table Customer table
addrOID addrOID custOID custOID
38 38 23 23
7 38 314 314
114 10 3 614
584 22 43 29
48 93 47 322
22 22 15 15
10 7 15 3

Database Application Programming With Java Technology Module 3, slide 30 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Exercise: OOAD and Database Design


• Objectives
• Tasks
• Summary

Database Application Programming With Java Technology Module 3, slide 31 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Describe the purpose of an object ID
• Describe two ways to create an object ID
• Given a class diagram, map objects to a relational
database
• Given a class diagram, map object relationships in the
database

Database Application Programming With Java Technology Module 3, slide 32 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Think Beyond
What additional features would you like to have available for
use in a database application?

Database Application Programming With Java Technology Module 3, slide 33 of 33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module 4

JDBC Advanced Topics

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 4, slide 2 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Exceptions
• The following elements are part of communicating
with a database.
• The application
• The JDBC code
• The database
• Errors are usually communicated using SQLException
or SQLWarning.

Database Application Programming With Java Technology Module 4, slide 3 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

SQLException
• SQLException can have a list of the following
exception objects:
• getNextException returns the next SQLException.
• getErrorCode returns an integer error code.
• getMessage returns a String error message.
• Possible failure points include the following:
• JDBC-server communication
• Incorrectly formatted commands
• Use of unsupported functions
• Referencing records that do not exist
Database Application Programming With Java Technology Module 4, slide 4 of 16
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

SQLWarning
• Generated for non-fatal SQL states
• Chained together
• Has the same methods as SQLException, but uses
getNextWarning instead of getNextException

Database Application Programming With Java Technology Module 4, slide 5 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Metadata
• Information about data, such as formatting or size
• Accessible through the JDBC API:
• Database metadata
• Result set metadata

Database Application Programming With Java Technology Module 4, slide 6 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Database Metadata
• Use the Connection.getMetaData method.
• Method returns DatabaseMetaData reference.
• Methods to retrieve the information include
isReadOnly.

Database Application Programming With Java Technology Module 4, slide 7 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Result Set Metadata


• Use the ResultSetMetaData.getMetaData method.
• Method returns ResultSetMetaData reference.
• Methods to retrieve the information include
getColumnCount.

Database Application Programming With Java Technology Module 4, slide 8 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Transactions
• A transaction is a logical group of work consisting of
one or more instructions.
• Use these steps for transactions with the JDBC API.
• Call the setAutoCommit method with a false value
• Perform one or more operations on the database
• To finalize the changes, call the commit method
• To drop the changes since the last commit, call the
rollback method

Database Application Programming With Java Technology Module 4, slide 9 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Transactions
• Syntax
1 Connection conRefVar = DriverManager.getConnection(urlString);
2 conRefVar.setAutoCommit(false);
3 Statement stmtRefVar = con.createStatement();
4 stmtRefVar.executeUpdate(sqlString);
5 conRefVar.transactionEndMethod;

• Example
1 try {
2 con.setAutoCommit(false);
3 Statement stmt = con.createStatement();
4 stmt.executeUpdate("INSERT INTO customer(1011,'XYZ Corporation')");
5 stmt.executeUpdate("INSERT INTO order(21,1011,12.43f)");
6 con.commit();
7 } catch (SQLException ex) {
8 try {
9 con.rollback();
10 } catch (SQLException ex2){}
11}

Database Application Programming With Java Technology Module 4, slide 10 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Concurrency Control
• Creating a transaction is handled through the
Connection interface.
• In a connection, you can set the transaction isolation
level to determine whether the following are allowed:
• Dirty reads
• Non-repeatable reads
• Phantom reads

Database Application Programming With Java Technology Module 4, slide 11 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Concurrency Control
• Methods to view and set isolation levels:
• getTransactionIsolation
• Connection.setTransactionIsolation
• Isolation-level static variables:
• TRANSACTION_NONE
• TRANSACTION_READ_UNCOMMITTED
• TRANSACTION_READ_COMMITTED
• TRANSACTION_REPEATABLE_READ
• TRANSACTION_SERIALIZABLE

Database Application Programming With Java Technology Module 4, slide 12 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Concurrency Control
• Syntax
conRefVar.setTransactionIsolation(Connection.isolationLevel);

• Example
1 Connection con;
2 con.setTransactionIsolation
(Connection.TRANSACTION_READ_UNCOMMITTED);
3 InitialContext initCtx =
Class.forName("oracle.jdbc.driver.OracleDriver");
4 con = DriverManager.getConnection
("jdbc:oracle:thin:@java1.com:1521:accounts", "marcl","mpuppet");

Database Application Programming With Java Technology Module 4, slide 13 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Exercise: JDBC Advanced Topics


• Objectives
• Tasks
• Summary

Database Application Programming With Java Technology Module 4, slide 14 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Write code to catch exceptions in JDBC processes
• View metadata for a table or result set
• Create transactions
• Use concurrency control to determine how data is read
and changed

Database Application Programming With Java Technology Module 4, slide 15 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Think Beyond
• What additional features would be useful in a database
application?

Database Application Programming With Java Technology Module 4, slide 16 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module 5

JDBC 2.0 Core Features

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 5, slide 2 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Enhancements to the JDBC 2.0 API


• JDBC 2.0 Core API – Provided in the java.sql package
• JDBC 2.0 Standard Extension API – Provided in the
javxa.sql package

Database Application Programming With Java Technology Module 5, slide 3 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Core API Enhancements


• Result set enhancements:
• Scrollability
• Updatability
• Statement enhancements for batch updates
• Advanced data types for SQL3

Database Application Programming With Java Technology Module 5, slide 4 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Result Set Enhancements


• Scrollability:
• Forward and backward scrolling
• Absolute and relative positioning
• Updatability

Database Application Programming With Java Technology Module 5, slide 5 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Scroll Settings
• In JDBC 1.0, ResultSet scrolling was forward only.
• In JDBC 2.0, a ResultSet can be:
• Forward only (same as JDBC 1.0) or forward and
backward enabled
• Scroll insensitive
• Scroll sensitive

Database Application Programming With Java Technology Module 5, slide 6 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Scroll Settings
Field Type Description
CONCUR_READ_ONLY static The concurrency mode for a
int ResultSet object that you
cannot update.
CONCUR_UPDATABLE static The concurrency mode for a
int ResultSet object that you can
update. You can update, insert,
and delete rows in an updatable
result set.
FETCH_FORWARD static The rows in a result set are
int processed in a forward direction;
first-to-last.
FETCH_REVERSE static The rows in a result set are
int processed in a reverse direction;
last-to-first.
FETCH_UNKNOWN static The order in which rows in a
int result set are processed is
unknown.
TYPE_FORWARD_ONLY static The type for a ResultSet object
int whose cursor can move only
forward.
TYPE_SCROLL_INSENSITIVE static The type for a ResultSet object
int that is scrollable but not sensitive
to changes made by others.
TYPE_SCROLL_SENSITIVE The type for a ResultSet object
that is scrollable and sensitive to
changes made by others.
Database Application Programming With Java Technology Module 5, slide 7 of 39
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Scroll Settings
• Syntax
Statement stmtRefVar = conRefVar.createStatement
(int resultSetType, int resultSetConcurrency);
ResultSet resultsetRefVar = stmtRefVar.executeQuery(sqlString);

• Examples
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement();
3 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

1 Connection con = DriverManager.getConnection("jdbc:odbc:accounts");


2 Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
3 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

1 Connection con = DriverManager.getConnection("jdbc:odbc:accounts");


2 Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
3 stmt.setFetchSize(25);
4 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

Database Application Programming With Java Technology Module 5, slide 8 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Positioning
• A ResultSet can support absolute and relative
positioning.
• Use methods such as absolute and next to position
cursor.

Database Application Programming With Java Technology Module 5, slide 9 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services
Positioning
Method Type Description
absolute(int row) boolean Moves the cursor to the given row
number in the result set.
afterLast() void Moves the cursor to the end of the
result set, just after the last row.
beforeFirst() void Moves the cursor to the front of the
result set, just before the first row.
first() boolean Moves the cursor to the first row in
the result set.
last() boolean Moves the cursor to the last row in
the result set.
next() boolean Moves the cursor down one row
from its current position.
previous() boolean Moves the cursor to the previous
row in the result set.
relative(int) boolean Moves the cursor a relative number
of rows, either positive or negative.
Method Type Description
isAfterLast() boolean Indicates whether the cursor is after
the last row in the result set.
isBeforeFirst() void Indicates whether the cursor is
before the first row in the result set.
isFirst() void Indicates whether the cursor is on
the first row of the result set.
isLast() boolean Indicates whether the cursor is on
the last row of the result set.
Database Application Programming With Java Technology Module 5, slide 10 of 39
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Updatability
• Updatability allows you to manipulate data using a
scroll cursor.
• A result set is updatable if the concurrency type is
CONCUR_UPDATABLE.
• You can update, delete, and insert rows in an updatable
ResultSet.
• Use scrolling methods to position the cursor on the row
to be updated or deleted.

Database Application Programming With Java Technology Module 5, slide 11 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Updating a Row
• Syntax
resultsetRefVar.updateXXX(column, value);
resultsetRefVar.updateRow();

• Example
1 rs.updateString(1, "100020");
2 rs.updateFloat("salary",60000.0f);
3 rs.updateRow();

Database Application Programming With Java Technology Module 5, slide 12 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Deleting a Row
• Syntax
resultsetRefVar.deleteRow();

• Example
1 rs.absolute(6);
2 rs.deleteRow();

Database Application Programming With Java Technology Module 5, slide 13 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Inserting a New Row


• Syntax
resultsetRefVar.movetoInsertRow();
resultsetRefVar.updateXXX(column, value);
resultsetRefVar.insertRow();

• Example
1 rs.moveToInsertRow(); rs.updateString(1, "100050");
2 rs.updateFloat(2, 80000.0f);
3 rs.insertRow();

Database Application Programming With Java Technology Module 5, slide 14 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Restrictions
Queries that meet the following criteria can have an
updatable result set.
• The query references one table.
• The query does not contain any join operations.
• The query selects the primary key.
• The query selects all columns that are non-nullable and
that do not have a default value.

Database Application Programming With Java Technology Module 5, slide 15 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement Enhancements for Batch


Updates
• The batch update feature allows you to submit multiple
update operations to a database for processing at once.
• The JDBC API cannot complete any task during batch
processing that would create a result set.
• You can use the following for batch updates.
• Statement
• PreparedStatement
• CallableStatement

Database Application Programming With Java Technology Module 5, slide 16 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
Submits a set of heterogeneous update commands to DBMS.

Database Application Programming With Java Technology Module 5, slide 17 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
• Syntax
Statement stmtRefVar = conRefVar.createStatement();
stmtRefVar.addBatch(sqlString);
// submit a batch of update commands for execution
intArrayRefVar = stmtRefVar.executeBatch();

• Example
1 con.setAutoCommit(false);
2 Statement stmt = con.createStatement();
3 stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Mays')");
4 stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
5 stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");
6 int[] updateCounts = stmt.executeBatch();
7 con.commit();

Database Application Programming With Java Technology Module 5, slide 18 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Statement
• A Statement object can track commands that can be
submitted together for execution.
• The Statement.executeBatch method submits a
batch of commands to DBMS for execution.
• The BatchUpdateException.getUpdateCounts
method can return an integer array of update counts
for the successful commands.

Database Application Programming With Java Technology Module 5, slide 19 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

PreparedStatement
• The batch update feature associates sets of input
parameter values with a PreparedStatement.
• Values can be sent to DBMS engine as a unit.

Database Application Programming With Java Technology Module 5, slide 20 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

PreparedStatement
• Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement
(sqlString);
pstmtRefVar.setXXXMethod(column, value);
pstmtRefVar.addBatch();
intArrayRefVar = pstmtRefVar.executeBatch();

• Example
1 con.setAutoCommit(false);
2 PreparedStatement stmt = con.prepareStatement
("INSERT INTO employees VALUES (?, ?)");
3 stmt.setInt(1, 2000);
4 stmt.setString(2, "Joe Mays");
5 stmt.addBatch();
6 stmt.setInt(1, 3000);
7 stmt.setString(2, "Kara Stelter");
8 stmt.addBatch();
9 // submit the batch for execution
10int[] updateCounts = stmt.executeBatch();
11con.commit();

Database Application Programming With Java Technology Module 5, slide 21 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

CallableStatement
• CallableStatement objects work the same way as
PreparedStatement objects.
• You can associate sets of input parameter values with a
callable statement and send them to the DBMS.

Database Application Programming With Java Technology Module 5, slide 22 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Advanced Data Types


• SQL3 types will be adopted in the next version of the
ANSI/ISO standard (American National Standards
Institute/International Organization for
Standardization).
• The JDBC 2.0 API provides interfaces for mapping
these to the Java programming language.

Database Application Programming With Java Technology Module 5, slide 23 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Advanced Data Types


• Blob – SQL BLOB
• Clob – SQL CLOB
• Array – SQL ARRAY
• Struct – SQL structure type
• Ref – SQL REF

Database Application Programming With Java Technology Module 5, slide 24 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Using SQL3 Data Types


Most operations on SQL3 types involve the getXXX, setXXX,
and updateXXX methods.
SQL3 Type getXXX setXXX updateXXX
ResultSet CallableStatement ResultSet
PreparedStatement
BLOB getBlob setBlob updateBlob
CLOB getClob setClob updateClob
ARRAY getArray setArray updateArray
Structured type getObject setObject updateObject
REF (structured type) getRef setRef updateRef

Database Application Programming With Java Technology Module 5, slide 25 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Arrays
1 ResultSet rs = stmt.executeQuery(
"SELECT scores FROM students WHERE id = 2238");
2 rs.next();
3 Array scores = rs.getArray("scores");

Database Application Programming With Java Technology Module 5, slide 26 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Arrays
1 import java.sql.*;
2
3 public class DBArray{
4 public static void main(String [] args){
5 try{
6 Class.forName("DriverClass");
7 Connection cnct = DriverManager.getConnection("ConnectInfo");
8 Statement stmt = cnct.createStatement();
9 // Create and execute the query
10 String dbQuery =
"SELECT scores FROM students WHERE id = 2238";
11 ResultSet rs = stmt.executeQuery(dbQuery);
12 // If you get a record back
13 if (rs.next()){
14 // Get array and store underlying Object reference.
15 // The object will be a type of array, but you must
16 // check for which type it is by using the instanceof
17 // keyword (unless you know the storage type in advance)
18 Array scores = rs.getArray("scores");
19 Object arrayVar = scores.getArray();

Database Application Programming With Java Technology Module 5, slide 27 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Arrays
20 // If the object reference is an array of float,
21 // cast it and retrieve all of the values, printing
22 // the result.
23 if (arrayVar instanceof float []){
24 float [] scoreValues = (float [])arrayVar;
25 for (int i = 0; i < scoreValues.length; i++){
26 System.out.println(scoreValues[i]);
27 }
28 }
29 }
30 }
31 catch (Exception exc){}
32 }
33}

Database Application Programming With Java Technology Module 5, slide 28 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Clob
1 import java.sql.*;
2 import java.io.*;
3
4 public class ReadDBClob{
5
6 public static void main(String [] args){
7
8 try{
9 Class.forName("str");
10 Connection cnct = DriverManager.getConnection("str");
11 Statement stmt = cnct.createStatement();
12 // Create and execute the query
13 String dbQuery = "SELECT notes FROM support_rec WHERE
id = 2238";
14 ResultSet rs = stmt.executeQuery(dbQuery);
15 // If you get a record back
16 if (rs.next()){

Database Application Programming With Java Technology Module 5, slide 29 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Clob
17 // Get the CLOB and use it to construct a BufferedReader
18 // (so that you can get the CLOB’s content. Clob
19 // is just a reference in Java; to use the underlying CLOB
20 // in the DB, you have to get an InputStream or Reader)
21 Clob sptNotes = rs.getClob("notes");
22 BufferedReader dbNote = new
BufferedReader(sptNotes.getCharacterStream());
23 String clobLine = dbNote.readLine();
24 // Echo the content to standard output
25 while (clobLine != null){
26 System.out.println(clobLine);
27 clobLine = dbNote.readLine();
28 }
29 }
30 }
31 catch (Exception exc){}
32 }
33}

Database Application Programming With Java Technology Module 5, slide 30 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Blob, Clob, and Array Objects


• You can manipulate them without bringing all data
from the server to the client.
• An instance of any type is a logical pointer to an object
in the database.
• Use SQL commands and the JDBC 1.0 and 2.0 API with
the objects as if they were actual objects in a database.
• To work with them as an object in the Java
programming language, bring all their data over to the
client.

Database Application Programming With Java Technology Module 5, slide 31 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Structured Types and Distinct Types


• Users can define SQL structured types and distinct
types.
• Use the SQL CREATE TYPE statement.

Database Application Programming With Java Technology Module 5, slide 32 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Structured Types
• SQL structured type members can be any data type.
• A Struct contains values for each attribute in the SQL
structured type.
• Use getObject and setObject with Struct instances.
• When retrieving a value using getObject, you get an
Object in the Java programming language that you
must explicitly cast to a Struct.
• Retrieve the internal values using the getAttributes
method.

Database Application Programming With Java Technology Module 5, slide 33 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Structured Types
1 CREATE TYPE PLANE_POINT
2 (
3 X FLOAT,
4 Y FLOAT
5 )

1 ResultSet rs = stmt.executeQuery(
"SELECT points FROM prices WHERE price > 3000.00");
2 while (rs.next()) {
3 Struct point = (Struct)rs.getObject("points");
4 // do something with point
5 }

Database Application Programming With Java Technology Module 5, slide 34 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Distinct Types
• A new type based on an existing type.
CREATE TYPE MONEY AS NUMERIC(10, 2)

• Mapped to the Java programming language type that


its underlying type would be mapped to.

Database Application Programming With Java Technology Module 5, slide 35 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

SQL3 Advanced Features


• The interface Struct is the standard mapping for a
SQL structured type.
• To simplify working with a SQL structured type, map
it to a class in the Java programming language.
• To reference a structured type, declare a SQL REF type
that represents a particular structured type.

Database Application Programming With Java Technology Module 5, slide 36 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Exercise: JDBC 2.0 Core Features


• Objectives
• Tasks
• Summary

Database Application Programming With Java Technology Module 5, slide 37 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• List the new features in the JDBC 2.0 Core API
• Explain how to scroll forward and backward within a
result set
• Understand how to use a scroll cursor to process the
results of a query
• Use a scroll cursor to manipulate data in the database
• Describe how to perform batch processing with
statements
• List the new data types added to JDBC 2.0

Database Application Programming With Java Technology Module 5, slide 38 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Think Beyond
• An application must specify a JDBC URL when
connecting to a database using the driver manager.
• Would this be restricting?
• What system could make it easier to change the URL?

Database Application Programming With Java Technology Module 5, slide 39 of 39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999 Revision A.1
Sun Educational Services

Module 6

JDBC 2.0 Standard Extensions

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 6, slide 2 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Standard Extension Enhancements to


the JDBC 2.0 API
• Support for JNDI
• Connection pooling
• Distributed transactions
• Row sets

Database Application Programming With Java Technology Module 6, slide 3 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

JNDI
• Java Naming and Directory Interface™ (JNDI)
provides a uniform way to access remote services.
• Remote services can be any enterprise service.
• JDBC 2.0 supports use of JNDI.

Database Application Programming With Java Technology Module 6, slide 4 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

JNDI Advantages
• With the driver manager:
• Code loading the driver is vendor specific
• Application needs to specify URL
• JNDI lets applications specify a logical name that
associates with a particular data source.
• The driver is specified with JNDI using two programs.
• One that associates the driver with a data source
name
• One that references that data source name

Database Application Programming With Java Technology Module 6, slide 5 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

JDBC DataSource
• A Java programming language object that implements
the javax.sql.DataSource interface.
• Examples include:
• Location of the database server
• Network protocol that communicates with the
server

Database Application Programming With Java Technology Module 6, slide 6 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

JDBC DataSource
Property Name Type Description
databaseName String Name of a database on a server
dataSourceName String Name of the class that
implements the data source
functionality
description String Description of this data source
networkProtocol String Network protocol used to
communicate with the server
password String A database password
portNumber int Port number where a server
listens for requests
roleName String The initial SQL role name
serverName String Database server name
user String User’s account name

Database Application Programming With Java Technology Module 6, slide 7 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

JDBC DataSource
• A data source is required to support the description
property.
• A data source object that supports a property must
supply accessor and mutator methods for it.
• A data source can contain a property not on the list of
standard properties.
• Register all JDBC data sources in one of the following:
• The jdbc naming subcontent of a JNDI namespace
• One of its child subcontexts

Database Application Programming With Java Technology Module 6, slide 8 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Registering a DataSource Object


You can create and manage a data source object within JNDI
separately from applications using it.
• Syntax
DataSourceClass dataSourceRefVar = new DataSourceClassConstructor();
dataSourceRefVar.mutatorMethod(serverName);
dataSourceRefVar.accessorMethod(databaseName);
Context contextRefVar = new InitialContext();
contextRefVar.bind (logicalDatasource, dataSourceRefVar);

• Example
1 SampleDataSource sds = new SampleDataSource();
2 sds.setServerName("akron");
3 sds.setDatabaseName("accounts-payable");
4 Context ctx = new InitialContext();
5 ctx.bind("jdbc/AccountMain", sds);

Database Application Programming With Java Technology Module 6, slide 9 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Establishing a Connection Using JNDI


After a data source is registered with JNDI, a JDBC
application can use it.
• Syntax
Context contextRefVar = new InitialContext();
DataSource dataSrcRefVar = (DataSource)contextRefVar.lookup
(logicalDataSrc);
Connection conRefVar = dataSrcRefVar.getConnection
("userID", "password");

• Example
1 Context ctx = new InitialContext();
2 DataSource ds = (DataSource)ctx.lookup("jdbc/AccountMain");
3 Connection con = ds.getConnection("marcl", "mpuppet");

Database Application Programming With Java Technology Module 6, slide 10 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Connection Pooling
• Is a cache of reusable database connections maintained
in memory.
• Does not require clients to register the driver.
• Is important for increasing performance.

Database Application Programming With Java Technology Module 6, slide 11 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Connection Pooling
Network
Application code
Client
(browser)
DataSource

Middle-tier server code

ConnectionPoolDataSource Network
DBMS
JDBC driver

Tier 1 Tier 2 Tier 3

Database Application Programming With Java Technology Module 6, slide 12 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Connection Pooling
• A driver vendor must implement the
javax.sql.ConnectionPoolDataSource interface.
• This interface and javax.sql.PooledConnection
interface provide "hooks" for third parties to
implement connection pooling.
• Hooks are used instead of a specific implementation
because JDBC users might use several connection
pooling algorithms.

Database Application Programming With Java Technology Module 6, slide 13 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Connecting
• Syntax
Connection conRefVar = dataSrcRefVar.getConnection
(logicalDataSrc, "userID", "password");
// Do all the work as a single transaction (optional).
conRefVar.setAutoCommit(false);
// Work is done using standard JDBC code as defined in the
// rest of the JDBC API.
conRefVar.commit();
// Close the connection. This returns the underlying physical
// database connection to the pool.
conRefVar.close();

• Example
1 Connection con = ds.getConnection("jdbc/webDatabase", "marcl", "mpuppet");
2 con.setAutoCommit(false);
// The actual work (queries and updates) would go here.
3 con.commit();
4 con.close();

Database Application Programming With Java Technology Module 6, slide 14 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Distributed Transactions
Distributed transactions allow a JDBC driver to support the
two-phase commit protocol used by the Java Transaction API
(JTA).

Database Application Programming With Java Technology Module 6, slide 15 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Architecture
Network
Application code
Client
(browser)
DataSource

Transaction manager
Middle-tier server code

XADataSource
Network DBMS
JDBC driver

Tier 1 Tier 2 Tier 3

Database Application Programming With Java Technology Module 6, slide 16 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Architecture
• Browser starts application code that runs in middle tier.
• The application code:
• Accesses databases in a distributed transaction
using the JDBC API
• Uses the DataSource interface to obtain a
Connection object
• The DataSource implementation:
• Sets up environment for the returned Connection
• Uses JDBC features to implement connection
caching and distributed transactions

Database Application Programming With Java Technology Module 6, slide 17 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Implementation
• A JDBC driver vendor implements:
• javax.sql.XADataSource
• javax.sql.XAConnection
• javax.sql.DataSource
• A middle-tier server vendor implements the
javax.sql.DataSource interface.
• The transaction infrastructure includes:
• Transaction manager
• JDBC driver supporting the JDBC 2.0 API

Database Application Programming With Java Technology Module 6, slide 18 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Implementation
• JDBC assumptions:
• Distributed transaction boundaries are controlled by
the middle-tier server, or another API.
• Distributed transactions are used by component-
based transactional applications in a modern
application server environment
• Application code must not call the
Connection.commit or Connection.rollback
methods.
• Connection object returned by a DataSource has
autocommit mode turned off by default.

Database Application Programming With Java Technology Module 6, slide 19 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Row Sets
• Encapsulate one or more rows retrieved from a tabular
data source
• Are a way to represent the rows so that they can be
used with the JavaBeans™ component model
• Can provide scrollable or updatable result sets when
the JDBC driver does not support them
• Must implement the javax.sql.RowSet interface
• Might keep a database connection
• Affiliated with a connection only while used for a
particular query

Database Application Programming With Java Technology Module 6, slide 20 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Types of Row Set Implementations


• Disconnected row set does not usually have connection
open.
• Connected row set keeps connection open for as long as
the row set is in use.

Database Application Programming With Java Technology Module 6, slide 21 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Properties
The RowSet interface provides a set of JavaBeans properties
that allow you to:
• Configure a RowSet instance to connect to a data source
• Retrieve a set of rows
1 rset = new RowSet();
2 rset.setDataSourceName("jdbc/SomeDataSourceName");
3 rset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
4 rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE");

Database Application Programming With Java Technology Module 6, slide 22 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Events
• Components can be notified when an event occurs.
• Registering a component requires implementing the
RowSetListener interface.
• Event listeners are registered using the
addRowSetListener method.
RowSetListener listener ...;
rset.addRowSetListener(listener);

• Row sets can generate three different types of events.


• Cursor movement events
• Row change events
• Row set change events

Database Application Programming With Java Technology Module 6, slide 23 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Parameters
• You can use the row set to execute queries and pass
values.
• setXXX methods let you pass input parameters to a row
set.
• Command property is typically specified at design
time; parameters are not set until runtime.
rset.setCommand("SELECT NAME, BREED, AGE FROM CANINE WHERE NAME = ?");
rset.setString(1, "spot");

Database Application Programming With Java Technology Module 6, slide 24 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Traversing a Row Set


• A RowSet is a ResultSet that can function as a
JavaBeans component.
• You can iterate through a row set as you can a result set.
1 // iterate forward through the row set
2 rset.beforeFirst();
3 while (rset.next()) {
4 System.out.println(rset.getString(1) + " " + rset.getFloat(2));
5 }

Database Application Programming With Java Technology Module 6, slide 25 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Command Execution
• To fill a row set, call the RowSet.execute method.
• Properties vary between implementations.
• The RowSet interface contains the properties for
connecting to a JDBC data source.
• Row set contents are lost when an execute method is
called.

Database Application Programming With Java Technology Module 6, slide 26 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Overview of Row Set Implementation


• A CachedRowSet class (currently available)
• A JDBCRowSet class
• A WebRowSet class

Database Application Programming With Java Technology Module 6, slide 27 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• List the features in the JDBC 2.0 Standard Extension
API
• Understand how to use Java Naming and Directory
Interface functionality to reduce the dependence of a
JDBC program on a particular driver
• Describe how connection pooling is used to connect an
application to a database
• Understand how distributed transactions work
• Explain how to use row sets to encapsulate rows for use
with the JavaBeans component model

Database Application Programming With Java Technology Module 6, slide 28 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Think Beyond
• What elements might be necessary in an
implementation of the CachedRowSet class?

Database Application Programming With Java Technology Module 6, slide 29 of 29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Module 7

Row Set Implementation

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 7, slide 2 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

CachedRowSet Class Overview


• Similar to a disconnected set of rows cached outside of
a data source
• Used as a container for tabular data
• Should not be used for extremely large data sets
• Can be passed between different components in a
distributed system
• Can provide scrolling and updating for ResultSets
without these features

Database Application Programming With Java Technology Module 7, slide 3 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

CachedRowSet Class Overview

Java client Tier 1

RMI/CORBA

CachedRowSet
Tier 2
JDBC

DBMS Tier 3

Database Application Programming With Java Technology Module 7, slide 4 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Creating a CachedRowSet
• A CachedRowSet is a JavaBean, so you can use a Beans
development tool to create them.
• Applications can create instances at runtime.

Database Application Programming With Java Technology Module 7, slide 5 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Retrieving Data
• A CachedRowSet object can contain:
• Data retrieved with a JDBC driver
• Data from some other source, such as a file
• You can get data into a CachedRowSet using the
CachedRowSet.populate method.
1 ResultSet rs = stmt.executeQuery
("SELECT NAME, SALARY FROM EMPLOYEE");
2 CachedRowSet crset = new CachedRowSet();
3 crset.populate(rs);

Database Application Programming With Java Technology Module 7, slide 6 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Retrieving Data
• You also can get data into a CachedRowSet object using
the execute method, which has two forms.
• You must always specify a command using the
command property.
• Call execute once you have set the appropriate
properties.
1 // There is already a connection associated
2 // with the CachedRowSet
3 CachedRowSet crset = new CachedRowSet();
4 crset.setCommand(
"SELECT year, model FROM car WHERE manufacturer = FORD");
5 crset.execute();

Database Application Programming With Java Technology Module 7, slide 7 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Accessing Data
• Access the contents of a CachedRowSet object with
methods inherited from the ResultSet interface.
• A CachedRowSet is always scrollable, and has type
ResultSet.

Database Application Programming With Java Technology Module 7, slide 8 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Modifying Data
• A CachedRowSet object tracks both its original value
and its current value.
• The original value is set by methods
CachedRowSet.execute and populate.
• Call the CachedRowSet.updateXXX methods to update
the current value of a CachedRowSet.

Database Application Programming With Java Technology Module 7, slide 9 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Modifying Data
1 // initialize the original and current values
2 crset.execute();
3 // update the current value of the first row
4 crset.first();
5 crset.updateString(1, "Joe Mays");
6 crset.updateFloat(2, 50000f);
7 crset.updateRow();
8 // update the current value of the sixth row
9 crset.relative(5);
10crset.updateString(1, "Kara Stelter");
11crset.updateFloat(2, 38000f);
12crset.updateRow();
13// update the original value and the database
14crset.acceptChanges();

Database Application Programming With Java Technology Module 7, slide 10 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Miscellaneous Methods
• The CachedRowSet.clone and
CachedRowSet.createCopy methods create a copy of
a row set independent from the original.
• The CachedRowSet.createShared method:
• Creates a row set that shares its state with the
original row set
• Allows an application to create multiple cursors
over a single set of rows
• CachedRowSets provide methods for conversion to a
Java technology collection.

Database Application Programming With Java Technology Module 7, slide 11 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Reading and Writing Data


• Row sets can be used with a reader/writer for
customized data retrieval and updating.
• Custom readers and writers enable a RowSet to read its
data from a different data source.
• A CachedRowSet implementation with a custom
reader/writer can be made available as a JavaBeans
component.

Database Application Programming With Java Technology Module 7, slide 12 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Reading and Writing Data


• When CachedRowSet.execute is called:
• The CachedRowSet invokes an object
• The readData method is called
• CachedRowSet exposes itself to RowSetReader
• When CachedRowSet.acceptChanges is called:
• CachedRowSet invokes an object that implements
the RowSetWriter interface
• RowSetWriter.writeData method is invoked to
write any changed data that has been changed
• setReader, setWriter register readers and writers.
Database Application Programming With Java Technology Module 7, slide 13 of 19
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Reading and Writing Data


CachedRowSet

data in data out

RowSetReader RowSetWriter

Data source*

*A database, spreadsheet, or other source of data

Database Application Programming With Java Technology Module 7, slide 14 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

RowSetReader
• A row set that supports the reader/writer paradigm
should:
• Implement the RowSetInternal interface
• Pass a reference to itself when invoking the
readData method
• The example readData method uses the calling row
set’s properties to create a Connection to a data source.
• An alternative reader implementation could read data
directly from a regular file.

Database Application Programming With Java Technology Module 7, slide 15 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

RowSetWriter
• Works with the reader shown previously
• Enforces optimistic concurrency control
• Calls the reader to create a Connection, and to find out
if it needs to reset itself
• Iterates through each row and updates the underlying
database when necessary

Database Application Programming With Java Technology Module 7, slide 16 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Exercise: Row Set Implementation


• Objectives
• Tasks
• Summary

Database Application Programming With Java Technology Module 7, slide 17 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Check Your Progress


• Explain how to use the CachedRowSet implementation
• Modify a RowSetReader or RowSetWriter
• Understand the benefit provided by using the
CachedRowSet implementation

Database Application Programming With Java Technology Module 7, slide 18 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Think Beyond
• What considerations should you take into account
when designing the architecture of your Java
application?

Database Application Programming With Java Technology Module 7, slide 19 of 19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999 Revision A.1
Sun Educational Services

Module 8

JDBC and Application Architecture

Database Application Programming With Java Technology October 1999


Sun Educational Services

Overview
• Objectives
• Relevance

Database Application Programming With Java Technology Module 8, slide 2 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Tiered Application Architecture


Overview
• A tier is a software module that supplies some part of
functionality for a full application.
• Separate tiers can let you update tiers independently.
• You can use tiers to coordinate multiple clients.

Database Application Programming With Java Technology Module 8, slide 3 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Tiered Application Architecture


Overview
Client

Client Middle DBMS


tier

Client

Database Application Programming With Java Technology Module 8, slide 4 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Tiers and Components


All architectures have three components:
• Presentation – Receives data processing requests;
typically in the first tier
• Business logic – Implements business rules:
• In the first tier in a two-tier model
• In the second tier in a three-tier or n-tier model
• Data – Stores and allows access to the data; typically in
the third tier

Database Application Programming With Java Technology Module 8, slide 5 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Two-Tier Architecture
• The database front end is in a separate tier from the
database engine.
• This architecture is a client/server configuration.
• If users need a different interface, only a new front end
needs to be developed.
• The client, or first tier, makes connections to additional
database servers.

Database Application Programming With Java Technology Module 8, slide 6 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Two-Tier Architecture

Client machine Presentation Applet or


component application
Business logic
component*

JDBC driver

DBMS
protocol

Database Data
server machine component DBMS

*You can store business logic on either tier or both tiers

Database Application Programming With Java Technology Module 8, slide 7 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Three-Tier Architecture
• Commands are sent to a middle tier of services.
• Middle tier sends SQL statements to the database.
• The database processes the SQL statements.
• The results are sent back to the middle tier.
• The middle tier sends the results to the user.

Database Application Programming With Java Technology Module 8, slide 8 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Three-Tier Architecture
• Enables using secure socket classes, caching data, and
managing business rules separately
• Enables rules to be kept in a single location
• Allows database connection pooling
• Enables managing connections among multiple data
sources
• Enables data synchronization
• Simplifies the client requirements

Database Application Programming With Java Technology Module 8, slide 9 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Three-Tier Architecture
Client machine Presentation Java applet or
component HTML browser

RMI/CORBA,
HTTP

Application server
Server machine Business logic
component (Java technology)

JDBC driver

DBMS
protocol

Database Data
server machine component DBMS

Database Application Programming With Java Technology Module 8, slide 10 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

N-Tier Architecture
• N-tier architectures extend other architectures by
continuing to break out functions into tiers.
• Create an n-tier architecture by dividing the
application vertically or horizontally.

Database Application Programming With Java Technology Module 8, slide 11 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

N-Tier Architecture
First tier First tier
Client Client

Caching control

Second tier Application server Print server

Second tier Application server

Third tier
DBMS
hird tier
DBMS

Database Application Programming With Java Technology Module 8, slide 12 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Two-Tier Architecture
• This architecture is typically suitable for small
applications.
• The client program is responsible for all error checking.
• On a network, data is exposed.
• Table changes require interface changes.
• Installing drivers requires more work.

Database Application Programming With Java Technology Module 8, slide 13 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Three-Tier and N-Tier Architecture


• The client is much thinner than on the two-tier
architecture.
• Locating the business rules in the middle tier eases
maintenance.
• Three or more tiers increase the number of possible
failure points.
• Overall application complexity increases.
• The three-tier or n-tier architecture is generally
preferred.

Database Application Programming With Java Technology Module 8, slide 14 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Check Your Progress


• Define the components in a multi-tier application
• Explain which components belong to each tier in a
multi-tier application
• Explain where JDBC components should be installed in
a multi-tier application
• Describe when to use a two-tier application
architecture in a database application
• Describe when to use a three-tier application
architecture
• Describe when to use an n-tier application architecture

Database Application Programming With Java Technology Module 8, slide 15 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Sun Educational Services

Think Beyond
• Based on this course, can you begin implementing
JDBC in your work?
• What other information would be useful to help you
get started?

Database Application Programming With Java Technology Module 8, slide 16 of 16


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services. October 1999, Revision A.1
Copyright 1999 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits réservés.

Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune partie de ce
produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.

Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun.
Des parties de ce produit pourront être dérivées du systèmes Berkeley 4.3 BSD licenciés par l’Université de Californie. UNIX est une marque déposée aux Etats-Unis et dans d’autres
pays et licenciée exclusivement par X/Open Company Ltd.

Sun, Sun Microsystems, le logo Sun, Java, JDBC, Java Naming and Directory Interface, et JavaBeans sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc.
aux Etats-Unis et dans d’autres pays.

Toutes les marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres pays.

Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.

UNIX est une marques déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company, Ltd.

L’interfaces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox
pour larecherche et le développement du concept des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive de Xerox sur
l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se
conforment aux licences écrites de Sun.

L’accord du gouvernement américain est requis avant l’exportation du produit.

Le système X Window est un produit de X Consortium, Inc.

LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT
EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A
L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.
Course Contents

About This Course .......................................................................................................Preface-1


Course Goal .................................................................................................................................. Preface-2
Course Overview ......................................................................................................................... Preface-3
Course Map ................................................................................................................................... Preface-4
Module-by-Module Overview ................................................................................................... Preface-5
Course Objectives ......................................................................................................................... Preface-7
Skills Gained by Module ............................................................................................................. Preface-8
Guidelines for Module Pacing ................................................................................................... Preface-9
Topics Not Covered ................................................................................................................... Preface-10
How Prepared Are You? ........................................................................................................... Preface-11
Introductions .............................................................................................................................. Preface-12
How to Use Course Materials .................................................................................................. Preface-13
Icons ............................................................................................................................................. Preface-14
Typographical Conventions ..................................................................................................... Preface-15
Syntax Conventions ................................................................................................................... Preface-16

JDBC Overview ......................................................................................................................1-1


Overview .................................................................................................................................................. 1-2
What Is the JDBC API? ........................................................................................................................... 1-3
Drivers ...................................................................................................................................................... 1-5
JDBC/ODBC Bridge Plus ODBC Driver ............................................................................................. 1-8
Native API .............................................................................................................................................. 1-10
JDBC-Net ................................................................................................................................................ 1-12
Native Protocol ...................................................................................................................................... 1-14
Finding Drivers ..................................................................................................................................... 1-16
JDBC Developer Interface .................................................................................................................... 1-17

Database Application Programming With Java Technology i


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

Classes and Interfaces ........................................................................................................................... 1-18


Identifying a Database Using a URL .................................................................................................. 1-20
Basic URL Syntax .................................................................................................................................. 1-21
jdbc ....................................................................................................................................................... 1-22
subprotocol ........................................................................................................................................ 1-23
Using a Network Naming Service as the Subprotocol .................................................................... 1-24
odbc Subprotocol .................................................................................................................................. 1-25
subname ................................................................................................................................................. 1-26
Connecting to a Remote Server ........................................................................................................... 1-27
Check Your Progress ............................................................................................................................ 1-28
Think Beyond ........................................................................................................................................ 1-29

Using JDBC ..............................................................................................................................2-1


Overview .................................................................................................................................................. 2-2
Creating a Basic JDBC Application ...................................................................................................... 2-3
Step 1 – Registering a Driver ................................................................................................................. 2-5
Using the Class Loader .......................................................................................................................... 2-6
Instantiating a Driver ........................................................................................................................... 2-7
Defining the jdbc.drivers Property ................................................................................................. 2-8
Using the -D Option With the java Command ................................................................................. 2-9
Choosing the Best Registration Approach ........................................................................................ 2-10
Step 2 – Establishing a Connection to the Database ........................................................................ 2-11
DriverManager.getConnection ..................................................................................................... 2-13
Driver.Connect ................................................................................................................................. 2-14
Step 3 – Creating a Statement .............................................................................................................. 2-16
Statement ............................................................................................................................................ 2-17
PreparedStatement ........................................................................................................................... 2-19
CallableStatement ........................................................................................................................... 2-21
Comparing Statement Interfaces ........................................................................................................ 2-23
Step 4 – Executing the SQL .................................................................................................................. 2-24
Statement ............................................................................................................................................ 2-25

Database Application Programming With Java Technology ii


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

Step 5 – Processing the Results ........................................................................................................... 2-27


Step 6 – Closing Down JDBC Objects ................................................................................................. 2-29
Exercise: Using JDBC ............................................................................................................................ 2-30
Check Your Progress ............................................................................................................................ 2-31
Think Beyond ........................................................................................................................................ 2-33

OOAD and Database Design ...............................................................................................3-1


Overview .................................................................................................................................................. 3-2
Module Overview ................................................................................................................................... 3-3
Object ID Overview ................................................................................................................................ 3-4
Object IDs and Primary Keys ................................................................................................................ 3-5
Single-row Table ..................................................................................................................................... 3-7
High/Low ................................................................................................................................................ 3-8
Object-Relational Mapping .................................................................................................................. 3-10
Mapping Classes to Tables .................................................................................................................. 3-12
One Table for Every Class ................................................................................................................... 3-14
One Table for Each Concrete Class .................................................................................................... 3-16
One Table for an Entire Class Hierarchy ........................................................................................... 3-18
Mapping Two Classes to One Table ................................................................................................... 3-21
Mapping Class Attributes to Table Columns ................................................................................... 3-22
Mapping Class Relationships to Tables ............................................................................................. 3-23
One-to-One Relationships .................................................................................................................... 3-24
One-to-Many Relationships ................................................................................................................. 3-27
Many-to-Many Relationships .............................................................................................................. 3-29
Exercise: OOAD and Database Design .............................................................................................. 3-31
Check Your Progress ............................................................................................................................ 3-32
Think Beyond ........................................................................................................................................ 3-33

JDBC Advanced Topics ..........................................................................................................4-1


Overview .................................................................................................................................................. 4-2
Exceptions ................................................................................................................................................ 4-3

Database Application Programming With Java Technology iii


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

SQLException ........................................................................................................................................ 4-4


SQLWarning ............................................................................................................................................ 4-5
Metadata ................................................................................................................................................... 4-6
Database Metadata .................................................................................................................................. 4-7
Result Set Metadata ................................................................................................................................ 4-8
Transactions ............................................................................................................................................. 4-9
Concurrency Control ............................................................................................................................ 4-11
Exercise: JDBC Advanced Topics ....................................................................................................... 4-14
Check Your Progress ............................................................................................................................ 4-15
Think Beyond ........................................................................................................................................ 4-16

JDBC 2.0 Core Features ..........................................................................................................5-1


Overview .................................................................................................................................................. 5-2
Enhancements to the JDBC 2.0 API ...................................................................................................... 5-3
Core API Enhancements ........................................................................................................................ 5-4
Result Set Enhancements ....................................................................................................................... 5-5
Scroll Settings .......................................................................................................................................... 5-6
Positioning ............................................................................................................................................... 5-9
Updatability ........................................................................................................................................... 5-11
Updating a Row .................................................................................................................................... 5-12
Deleting a Row ...................................................................................................................................... 5-13
Inserting a New Row ............................................................................................................................ 5-14
Restrictions ............................................................................................................................................. 5-15
Statement Enhancements for Batch Updates .................................................................................... 5-16
Statement ............................................................................................................................................ 5-17
PreparedStatement ........................................................................................................................... 5-20
CallableStatement ........................................................................................................................... 5-22
Advanced Data Types .......................................................................................................................... 5-23
Using SQL3 Data Types ....................................................................................................................... 5-25
Arrays ..................................................................................................................................................... 5-26
Clob ....................................................................................................................................................... 5-29

Database Application Programming With Java Technology iv


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

Blob, Clob, and Array Objects ........................................................................................................... 5-31


Structured Types and Distinct Types ................................................................................................. 5-32
Structured Types ................................................................................................................................... 5-33
SQL3 Advanced Features .................................................................................................................... 5-36
Exercise: JDBC 2.0 Core Features ........................................................................................................ 5-37
Check Your Progress ............................................................................................................................ 5-38
Think Beyond ........................................................................................................................................ 5-39

JDBC 2.0 Standard Extensions .............................................................................................6-1


Overview .................................................................................................................................................. 6-2
Standard Extension Enhancements to the JDBC 2.0 API .................................................................. 6-3
JNDI .......................................................................................................................................................... 6-4
JNDI Advantages .................................................................................................................................... 6-5
JDBC DataSource .................................................................................................................................. 6-6
Registering a DataSource Object ......................................................................................................... 6-9
Establishing a Connection Using JNDI .............................................................................................. 6-10
Connection Pooling .............................................................................................................................. 6-11
Distributed Transactions ...................................................................................................................... 6-15
Architecture ........................................................................................................................................... 6-16
Implementation ..................................................................................................................................... 6-18
Row Sets ................................................................................................................................................. 6-20
Types of Row Set Implementations .................................................................................................... 6-21
Properties ............................................................................................................................................... 6-22
Events ...................................................................................................................................................... 6-23
Parameters .............................................................................................................................................. 6-24
Traversing a Row Set ............................................................................................................................ 6-25
Command Execution ............................................................................................................................ 6-26
Overview of Row Set Implementation .............................................................................................. 6-27
Check Your Progress ........................................................................................................................... 6-28
Think Beyond ........................................................................................................................................ 6-29

Database Application Programming With Java Technology v


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Sun Educational Services

Row Set Implementation ......................................................................................................7-1


Overview .................................................................................................................................................. 7-2
CachedRowSet Class Overview ............................................................................................................ 7-3
Creating a CachedRowSet ..................................................................................................................... 7-5
Retrieving Data ........................................................................................................................................ 7-6
Accessing Data ........................................................................................................................................ 7-8
Modifying Data ....................................................................................................................................... 7-9
Miscellaneous Methods ........................................................................................................................ 7-11
Reading and Writing Data ................................................................................................................... 7-12
RowSetReader ...................................................................................................................................... 7-15
RowSetWriter ...................................................................................................................................... 7-16
Exercise: Row Set Implementation ..................................................................................................... 7-17
Check Your Progress ........................................................................................................................... 7-18
Think Beyond ........................................................................................................................................ 7-19

JDBC and Application Architecture ....................................................................................8-1


Overview .................................................................................................................................................. 8-2
Tiered Application Architecture Overview ........................................................................................ 8-3
Tiers and Components ........................................................................................................................... 8-5
Two-Tier Architecture ............................................................................................................................ 8-6
Three-Tier Architecture .......................................................................................................................... 8-8
N-Tier Architecture ............................................................................................................................... 8-11
Two-Tier Architecture .......................................................................................................................... 8-13
Three-Tier and N-Tier Architecture ................................................................................................... 8-14
Check Your Progress ............................................................................................................................ 8-15
Think Beyond ........................................................................................................................................ 8-16

Database Application Programming With Java Technology vi


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1

You might also like