SL330 - Database Application Programming With Java - Oh - 1099
SL330 - Database Application Programming With Java - Oh - 1099
SL-330
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.
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.
Preface
Course Goal
This course provides you with knowledge and skills to:
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
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”
Module-by-Module Overview
• Appendix A – “Database Basics”
• Appendix B – “Using SQLJ”
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
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
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
Icons
Additional resources
Demonstration
Discussion
Typographical Conventions
• Courier is used for the names of commands, files, and
directories, as well as on-screen computer output.
Syntax Conventions
• Syntax and example
type varIdentifier
int myFirstVariable;
• Italicized variables
class className
Module 1
JDBC Overview
Overview
• Objectives
• Relevance
Drivers
• Are a collection of classes implementing JDBC classes
and interfaces
• Provide a class that has implemented the
java.sql.Driver interface
Drivers
Java application
(JDBC API)
ODBC and
DB drivers
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
JDBC API
Client Server
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.
Native API
Application
JDBC API
Native code
libraries Database
Client Server
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.
JDBC-Net
Application
JDBC API
DBMS-specific
JDBC-Net translator Database
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
Native Protocol
Application
JDBC API
Client Server
Finding Drivers
http://java.sun.com/products/jdbc/drivers.html
• Example
jdbc:odbc:wombat
jdbc
• Always jdbc
subprotocol
• Is the name of the driver or the type of database
connectivity mechanism
• Is often odbc
• Can be the network naming service
• Example
jdbc:dcenaming:accounts-payable
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
subname
• Identifies the database
• Can have a subsubname
• Example
jdbc:dbnet://wombat:3560/fred
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.
Module 2
Using JDBC
Overview
• Objectives
• Relevance
• Example
Class.forName("oracle.jdbc.driver.OracleDriver");
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();
• Example
jdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver
• Example
java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver
Connection Process
getConnection(urlString)
DriverManager
Application
connect(urlString)
Connection
null null
Successful
connection
accounts
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");
Driver.Connect
• Makes a direct call to a specific Driver object.
• Avoids the problems of standard approach.
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}
Statement
Get a Statement object from the
Connection.createStatement method.
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’");
PreparedStatement
• A precompiled SQL statement that is more efficient
than repeatedly calling the same SQL statement.
• Extends Statement.
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();
CallableStatement
• Lets you execute non-SQL statements against the
database.
• Extends PreparedStatement.
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}
Statement
• executeQuery(sqlString)
• executeUpdate(sqlString)
• execute(sqlString)
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");
• 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 }
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?
Module 3
Overview
• Objectives
• Relevance
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
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.
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.
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
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.
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
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.
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.
Many-to-Many Relationships
• Address to Customer is a many-to-many relationship.
• You could create a join table containing customerOID
and addressOID.
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
Think Beyond
What additional features would you like to have available for
use in a database application?
Module 4
Overview
• Objectives
• Relevance
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.
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
Metadata
• Information about data, such as formatting or size
• Accessible through the JDBC API:
• Database metadata
• Result set metadata
Database Metadata
• Use the Connection.getMetaData method.
• Method returns DatabaseMetaData reference.
• Methods to retrieve the information include
isReadOnly.
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
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}
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
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
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");
Think Beyond
• What additional features would be useful in a database
application?
Module 5
Overview
• Objectives
• Relevance
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
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");
Positioning
• A ResultSet can support absolute and relative
positioning.
• Use methods such as absolute and next to position
cursor.
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.
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();
Deleting a Row
• Syntax
resultsetRefVar.deleteRow();
• Example
1 rs.absolute(6);
2 rs.deleteRow();
• Example
1 rs.moveToInsertRow(); rs.updateString(1, "100050");
2 rs.updateFloat(2, 80000.0f);
3 rs.insertRow();
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.
Statement
Submits a set of heterogeneous update commands to DBMS.
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();
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.
PreparedStatement
• The batch update feature associates sets of input
parameter values with a PreparedStatement.
• Values can be sent to DBMS engine as a unit.
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();
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.
Arrays
1 ResultSet rs = stmt.executeQuery(
"SELECT scores FROM students WHERE id = 2238");
2 rs.next();
3 Array scores = rs.getArray("scores");
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();
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}
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()){
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}
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.
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 }
Distinct Types
• A new type based on an existing type.
CREATE TYPE MONEY AS NUMERIC(10, 2)
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?
Module 6
Overview
• Objectives
• Relevance
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.
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
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
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
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
• 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);
• Example
1 Context ctx = new InitialContext();
2 DataSource ds = (DataSource)ctx.lookup("jdbc/AccountMain");
3 Connection con = ds.getConnection("marcl", "mpuppet");
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.
Connection Pooling
Network
Application code
Client
(browser)
DataSource
ConnectionPoolDataSource Network
DBMS
JDBC driver
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.
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();
Distributed Transactions
Distributed transactions allow a JDBC driver to support the
two-phase commit protocol used by the Java Transaction API
(JTA).
Architecture
Network
Application code
Client
(browser)
DataSource
Transaction manager
Middle-tier server code
XADataSource
Network DBMS
JDBC driver
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
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
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.
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
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");
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);
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");
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.
Think Beyond
• What elements might be necessary in an
implementation of the CachedRowSet class?
Module 7
Overview
• Objectives
• Relevance
RMI/CORBA
CachedRowSet
Tier 2
JDBC
DBMS Tier 3
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.
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);
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();
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.
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.
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();
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.
RowSetReader RowSetWriter
Data source*
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.
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
Think Beyond
• What considerations should you take into account
when designing the architecture of your Java
application?
Module 8
Overview
• Objectives
• Relevance
Client
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.
Two-Tier Architecture
JDBC driver
DBMS
protocol
Database Data
server machine component DBMS
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.
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
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
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.
N-Tier Architecture
First tier First tier
Client Client
Caching control
Third tier
DBMS
hird tier
DBMS
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.
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?
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.
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