SL-330 Database Application Programming With Java 1999
SL-330 Database Application Programming With Java 1999
SL-330 Database Application Programming With Java 1999
SL-330
Student Guide
Please
Recycle
Contents
About This Course ......................................................................................ix
Course Goal .........................................................................................ix
Course Overview ................................................................................. x
Course Map......................................................................................... xii
Module-by-Module Overview ....................................................... xiii
Course Objectives.............................................................................. xvi
Skills Gained by Module................................................................ xvii
Guidelines for Module Pacing ..................................................... xviii
Topics Not Covered.......................................................................... xix
How Prepared Are You?................................................................... xx
Introductions ..................................................................................... xxi
How to Use Course Materials ........................................................ xxii
Course Icons and Typographical Conventions ......................... xxiv
Icons ......................................................................................... xxiv
Typographical Conventions ...................................................xxv
Syntax Conventions ............................................................... xxvi
JDBC Overview ........................................................................................1-1
Objectives ...........................................................................................1-1
Relevance............................................................................................ 1-2
References .......................................................................................... 1-3
What Is the JDBC API? ..................................................................... 1-4
Drivers ................................................................................................ 1-7
Overview ....................................................................................1-7
Type 1 JDBC/ODBC Bridge Plus ODBC Driver .............1-10
Type 2 Native API................................................................1-12
Type 3 JDBC-Net ..................................................................1-14
Type 4 Native Protocol........................................................1-16
Finding Drivers .......................................................................1-18
JDBC Developer Interface.............................................................. 1-19
Packages ...................................................................................1-19
Classes and Interfaces.............................................................1-20
iii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Identifying a Database Using a URL............................................ 1-24
Overview ..................................................................................1-24
Basic URL Syntax ....................................................................1-26
jdbc...........................................................................................1-27
subprotocol ...........................................................................1-28
subname ...................................................................................1-30
Connecting to a Remote Server.............................................1-31
Check Your Progress ...................................................................... 1-32
Think Beyond .................................................................................. 1-33
Using JDBC ................................................................................................2-1
Objectives ...........................................................................................2-1
Relevance............................................................................................ 2-2
Creating a Basic JDBC Application ................................................ 2-3
Step 1 Registering a Driver ........................................................... 2-6
Overview ....................................................................................2-6
Using the Class Loader...........................................................2-8
Instantiating a Driver..............................................................2-9
Using the jdbc.drivers Property ......................................2-11
Choosing the Best Registration Approach ..........................2-14
Step 2 Establishing a Connection to the Database .................. 2-15
Connection Process.................................................................2-15
DriverManager.getConnection........................................2-18
Driver.connect.....................................................................2-20
Step 3 Creating a Statement........................................................ 2-22
Statement................................................................................2-23
PreparedStatement..............................................................2-25
CallableStatement..............................................................2-27
Comparing Statement Interfaces ..........................................2-29
Step 4 Executing the SQL Statement ......................................... 2-30
Statement................................................................................2-31
PreparedStatement and CallableStatement................2-32
Step 5 Processing the Results ..................................................... 2-33
Step 6 Closing Down JDBC Objects........................................... 2-35
Exercise: Using JDBC...................................................................... 2-37
Tasks .........................................................................................2-37
Exercise Summary...................................................................2-38
Check Your Progress ...................................................................... 2-39
Think Beyond .................................................................................. 2-40
OOAD and Database Design ..................................................................3-1
Objectives ...........................................................................................3-1
Relevance............................................................................................ 3-2
References .......................................................................................... 3-3
Module Overview ............................................................................. 3-4
Object ID Overview .......................................................................... 3-5
Object IDs and Primary Keys .......................................................... 3-6
v
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Result Set Enhancements ................................................................. 5-5
Scrollability ................................................................................5-6
Updatability .............................................................................5-14
Statement Enhancements for Batch Updates .............................. 5-19
Statement................................................................................5-20
PreparedStatement..............................................................5-24
CallableStatement..............................................................5-26
Advanced Data Types .................................................................... 5-27
Overview ..................................................................................5-27
Using SQL3 Data Types .........................................................5-29
Blob, Clob, and Array Objects .............................................5-32
Structured Types and Distinct Types...................................5-34
Structured Types .....................................................................5-35
Distinct Types ..........................................................................5-37
SQL3 Advanced Features ......................................................5-39
Exercise: JDBC 2.0 Core Features.................................................. 5-40
Tasks .........................................................................................5-40
Exercise Summary...................................................................5-41
Check Your Progress ...................................................................... 5-42
Think Beyond .................................................................................. 5-43
JDBC 2.0 Standard Extensions ................................................................6-1
Objectives ...........................................................................................6-1
Relevance............................................................................................ 6-2
References .......................................................................................... 6-3
Standard Extension Enhancements to the JDBC 2.0 API ............ 6-4
JNDI .................................................................................................... 6-5
Overview ....................................................................................6-5
JNDI Advantages ......................................................................6-6
JDBC DataSource.....................................................................6-8
Registering a DataSource Object .........................................6-12
Establishing a Connection Using JNDI................................6-14
Connection Pooling ........................................................................ 6-16
Overview ..................................................................................6-16
Connecting ...............................................................................6-19
Distributed Transactions................................................................ 6-20
Overview ..................................................................................6-20
Architecture .............................................................................6-21
Implementation .......................................................................6-23
Row Sets ........................................................................................... 6-26
Overview ..................................................................................6-26
Types of Row Set Implementations......................................6-28
Row Sets at Design Time........................................................6-30
Row Sets at Runtime...............................................................6-35
vii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
SQL Basics ....................................................................................... A-13
Overview .................................................................................A-13
SELECT Statement...................................................................A-14
INSERT Statement...................................................................A-17
DELETE Statement...................................................................A-18
UPDATE Statement...................................................................A-18
Using SQLJ ................................................................................................ B-1
Objectives .......................................................................................... B-1
References ......................................................................................... B-2
SQLJ Overview ................................................................................. B-3
SQLJ Architecture ............................................................................ B-4
How SQLJ Works ............................................................................. B-5
Using SQLJ ........................................................................................ B-7
Registering and Connecting to the Database Using
Database Connection Management............................................ B-8
Creating a Statement Using SQLJ Clauses and Host
Variables....................................................................................... B-12
SQLJ Clauses........................................................................... B-12
Host Variables ....................................................................... B-13
Executing the Query and Reviewing the Result Set
Using Iterator Objects................................................................. B-14
Defining an Iterator Class ..................................................... B-14
Using an Iterator Class .......................................................... B-15
Glossary ....................................................................................... Glossary-1
Course Goal
Database Application Programming With Java Technology is a focused-
technology course that provides you with a hands-on approach to
developing database applications using Java technology and the
JDBC application programming interface (API). You will learn to use
the features of the JDBC 1.0 API, and will learn about the new features
added in JDBC 2.0.
ix
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Course Overview
The JDBC API is a set of specifications that tell database vendors how
to enable Java applications to perform operations on their databases,
and allow you to write Java applications that connect to any database
that provides drivers.
You will also learn how to choose the correct application architecture
for use with JDBCtwo-tier, three-tier, or n-tierand how to map that
applications objects to tables in a database.
The following course map enables you to see what you have
accomplished and where you are going in reference to the course
goals.
This module describes how the JDBC API is used, and how it
enables a Java application to connect to a database.
The skills for Database Application Programming With Java Technology are
shown in column 1 of the following matrix. The black boxes indicate
the main coverage for a topic; the gray boxes indicate the topic is
briefly discussed.
Module
Skills Gained 1 2 3 4 5 6 7 8
This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services:
To be sure you are prepared to take this course, can you perform the
topics shown on the above overhead?
Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.
Icons
Additional resources Indicates additional reference materials are
available.
Exercise objective Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.
Typographical Conventions
Courier is used for the names of commands, files, and directories, as
well as on-screen computer output. For example:
Courier bold is used for characters and numbers that you type. For
example:
system% su
Password:
Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:
Syntax Conventions
Whenever possible, both the syntax of a particular language element
and an example are shown. The following example of this approach
shows the syntax, then an example of declaring an integer variable.
type varIdentifier
int myFirstVariable;
The first line shown, typically with elements in italics, is the syntax;
the second line is the example.
Any elements shown in italics are variables, which must have values
substituted for them.
class className
Objectives
Upon completion of this module, you should be able to:
1-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
1
Relevance
The JDBC API is a set of classes and interfaces provided in the Java 2
Software Development Kit (J2SDK). JDBC has been included since
JDK 1.1 was released. Since its first release, JDBC has had one major
revision. JDK 1.1 comes with JDBC 1.0, while the J2SDK includes JDBC
2.0.
There are two major components of JDBC, the developer interface and
the implementation interface. This course concentrates on the
developer interface.
Drivers
Overview
A JDBC driver is a collection of classesthat implement the JDBC
interfaces required to connect a Java application to a database. Each
database driver must provide a class that has implemented the
java.sql.Driver interface. The database driver class then is used by
the generic java.sql.DriverManager class when it needs a driver to
connect to a particular database using a URL string.
The JDBC driver test suite is provided for driver vendors. Only drivers
that pass the JDBC driver test suite can be designated JDBC
Compliant. You can download the driver test suite from the
following site:
http://java.sun.com/marketing/enterprise/jdbc.html
Overview
The JDBC API is patterned after the open database connectivity model
(ODBC), which makes providing a JDBC implementation on top of
ODBC very small and efficient (Figure 1-1). ODBC is a standardized
API for accessing databases; it provides similar functionality as the
JDBC API for traditional languages, such as C and C++.
Figure 1-1 illustrates how a single Java application (or applet) can
access multiple database systems through one or more drivers.
Java application
JDBC API
ODBC and
DB drivers
Overview
JDBC drivers generally fit into one of four categories shown in
Table 1-1.
Drivers
The bridge gives JDBC access to the database using an existing ODBC
driver. The ODBC driver uses native code that must be installed on
each database client. Therefore, this driver is most appropriate for
corporate networks where client installations are not a major problem,
or for an application server in a three-tier architecture.
The disadvantage to this approach is that the application code calls the
JDBC driver manager, which invokes the JDBC driver. The driver calls
the ODBC driver manager, which invokes the ODBC driver, who
finally contacts the database. Failure can occur at several points in this
system.
Application
Database
JDBC API
Client Server
Drivers
Application
JDBC API
Native code
libraries Database
Client Server
Figure 1-3 Native API
Drivers
Type 3 JDBC-Net
This kind of driver communicates with an intermediary server seated
between the client and the database, using a network protocol that is
specific to the intermediary. These calls are translated by the
intermediary to DBMS-specific calls and forwarded to the database.
You do not need to install native code on the database client machines,
because you can implement the driver using only Java technology. If
the intermediary can talk to different DBMSs, you need only one JDBC
driver.
Type 3 JDBC-Net
Figure 1-4 illustrates a system using this driver.
Application
JDBC API
DBMS-specific
JDBC-Net translator Database
Drivers
This type of driver might give the best performance, but falls short for
the same reasons as the native API drivers: there is no flexibility to
allow for switching to different types of DBMSs.
Application
JDBC API
Client Server
Figure 1-5 Native Protocol
Finding Drivers
To view the latest information about drivers, check the following JDBC
Web page:
http://java.sun.com/products/jdbc/drivers.html
The first vendors with category 3 drivers available were SCO, Open
Horizon, Visigenic, and WebLogic.
Packages
The JDBC API is expressed as a series of Java technology interfaces, in
the following packages:
java.sql Contains the classes and interfaces used for the base
functionality of JDBC
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
DriverManager Class
Driver Interface
Connection Interface
ResultSet Interface
The classes and interfaces in the JDBC Core API are shown in
Figure 1-6.
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
Overview
A JDBC URL provides a way of identifying a database so that the
appropriate driver can recognize it and establish a connection with it.
The protocol, subprotocol, and specific data source are identified in the
URL. For example, the URL jdbc:odbc:fred indicates that the driver
should use the jdbc protocol to connect to an ODBC-type data source
named fred.
Overview
The JDBC URL mechanism is intended to provide a framework so that
different drivers can use different naming systems that are appropriate
for their needs. Each driver need only understand a single URL
naming syntax, and can reject any other URLs that it encounters. The
conventions are flexible, implementing the following features.
JDBC URLs also allow a level of indirection. This means that the
JDBC URL can refer to a logical host or database name that is
dynamically translated to the actual name by a network naming
system.
URL syntax
jdbc:subprotocol:subname
Example
jdbc:odbc:wombat
jdbc
This is the protocol. The protocol in a JDBC URL is always jdbc.
subprotocol
This is the name of the driver or the type of database connectivity
mechanism, which can be supported by one or more drivers. Different
drivers must have a different subprotocol identifier for the
DriverManager to be able to distinguish among them.
subprotocol
To specify a network naming service (so that the database name in the
JDBC URL does not have to be its actual name), use the subprotocol.
Example
jdbc:dcenaming:accounts-payable
In this example, the URL specifies that the local DCE naming service
should resolve the database name accounts-payable into a more
specific name that can be used to connect to the real database.
Note To use a network naming system, JNDI and the JDBC 2.0
standard extensions must be installed. These are covered in Module 6,
JDBC 2.0 Standard Extensions.
odbc Subprotocol
Syntax
jdbc:odbc:dataSrcName[;attributeName=attributeValue]
Example
subname
The subname provides enough information to locate the database. The
subname is determined by the driver vendor doing the
implementation (identified by the subprotocol).
Example
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
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.
Objectives
Upon completion of this module, you should be able to:
Note Module 5, JDBC 2.0 Core Features and Module 6, JDBC 2.0
Standard Extensions, cover the functionality that is available only in
the latest JDBC release.
2-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
2
Relevance
Now that you have learned the components of the JDBC API in
Module 1, JDBC Overview, the next step is to develop the code to
request and return information from a relational database
management system (RDBMS). The six main steps are as follows:
Note This list and the following sections cover the standard methods
for using the JDBC API to connect with and retrieve data from a
database. The information is not specific to versions 1.0 or 2.0.
Advanced features of JDBC 1.0, and the enhancements added with
JDBC 2.0, are covered in subsequent modules.
// 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();
Overview
The driver makes the connection to the database through the
DriverManager class. When attempting to connect to a database, the
JDBC API uses the first driver it finds that can successfully connect to
the given URL. Registering the driver is simple but critical, because
without the driver, you cannot make a connection to the database.
Instantiate a driver
Note You need to gain access to the JDBC interfaces before you
begin. To do so, be sure to import the java.sql package, or only the
classes in that package that you need.
To load the driver using the Class loader, call the driver name using
the complete path.
Syntax
Class.forName(driverName);
Example
Instantiating a Driver
If you need an explicit reference to the Driver object, use the new
keyword to register the driver. You do not need to associate the driver
object with a variable, because it exists in memory and is accessible to
the DriverManager.
Syntax
Driver drvRefVar = new DriverConstructor;
Example
This example registers the driver with the driver manager, which
subsequently manages the driver for the JVM session. It is not
necessary to retain a reference to the created object.
Driver drv = new oracle.jdbc.driver.OracleDriver();
Syntax
jdbc.drivers = driverName[:driverName]
Example
jdbc.drivers = oracle.jdbc.driver.OracleDriver:acme.cool.Driver
When attempting to connect to a database, the JDBC API uses the first
driver it finds that can successfully connect to the given URL. It first
tries each driver specified in the properties list, in order from left to
right. It then tries any drivers that are already loaded in memory, in
the order that the drivers were loaded.
You can register the driver by loading it into the system properties. To
use this method, specify the name=value pair (the name is always
jdbc.drivers and the value is the driver name).
Syntax
java -Djdbc.drivers=driverName[:driverName]
Example
java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver:acme.cool.Driver
Connection Process
The steps for establishing a connection occur in the following order:
Properties list
Memory
Connection Process
4. If the driver does not match, null is returned and the next driver
is checked.
Connection Process
Figure 2-1 illustrates how a DriverManager resolves a URL string
passed in the getConnection method. When the driver returns a null,
the driver manager continues to call the next registered driver until
either the list is exhausted or a Connection object is returned.
getConnection(urlString)
DriverManager
Application
connect(urlString)
Connection
null null
Successful
connection
accounts
DriverManager.getConnection method
Driver.connect method
DriverManager.getConnection
There are three getConnection methods; you can use any of them to
establish a connection:
getConnection (urlString)
getConnection (urlString, PropertiesObject)
getConnection (urlString, user, password)
Syntax
Connection conRefVar = DriverManager.getConnection(arguments);
DriverManager.getConnection
Example
Driver.connect
The Driver.connect method attempts to make a database connection
to the given URL.
Driver.connect
Syntax
Connection conRefVar = Driver.connect(urlString, PropertiesInfo);
Example
Statement
To submit a standard query, first get a Statement object from the
Connection.createStatement method.
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");
Statement
PreparedStatement
If the same SQL statements are executed multiple times, use a
PreparedStatement object. A prepared statement is a precompiled SQL
statement that is more efficient than calling the same SQL statement
over and over. The SQL statement is parsed only once. The
PreparedStatement interface extends the Statement interface to add
the capability of passing parameters inside of a statement.
Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement(sqlString);
You can use question marks within the SQL statement as placeholders
for data values.
PreparedStatement
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
A callable statement allows non-SQL statements (such as stored
procedures) to be executed against the database. The
CallableStatement interface extends the PreparedStatement
interface, which provides the methods for setting IN parameters.
Because the PreparedStatement interface extends the Statement
interface, methods for retrieving multiple results with a stored
procedure are supported with the Statement.getMoreResults
method.
Syntax
CallableStatement cstmtRefVar = conRefVar.prepareCall(sqlString);
CallableStatement
Example
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);
When you submit the SQL statement to the database, the JDBC API
passes the SQL statement to the underlying database connection
unaltered. The JDBC API does not attempt to interpret queries.
Statement
You can use several approaches to execute the SQL statement.
Statement
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");
To retrieve data from the ResultSet object that was returned, use its
assessor methods, which enable access to the various column values of
the current row. One method is provided for each SQL type.
You can retrieve these values using either a column name or an index.
You should use an index when referencing a column. When you use a
name to reference a column, one or more columns could have the same
name, which causes a conflict. Indexes begin at 1.
Refer to the Java 2 Specification API for the getXXX methods to access
columns within the ResultSet. These include getBoolean(int
columnIndex), getByte(int columnIndex), and getInt(int
columnIndex).
To retrieve data from the ResultSet object, you must be familiar with
the columns returned and their data types. A table mapping Java types
to SQL data types is provided in Table 3-1 of Module 3, OOAD and
Database Design.
Syntax
1 while (resultsetRefVar.next()) {
2 System.out.println ("column: " +
resultsetRefVar.getXXXMethod(column));
3 }
Example
After each connection and retrieval of data, close down the following
JDBC objects:
Note Be sure that you do the closing down inside a finally block of
exception handling to ensure that the objects are closed when you exit.
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
3-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
3
Relevance
Module Overview
This module describes how to deal with these issues, through object
IDs (OIDs) and object-relational mapping.
Object ID Overview
This section describes object IDs (OIDs), which are unique record
identifiers that have no business meaning, and explains how they can
be used more effectively than other indexes, such as primary keys, to
uniquely identify objects (records) in one or more databases.
Using primary keys has the advantage of being easy to implement and
maintain. OIDs, on the other hand, must be generated and maintained
outside of individual tables. However, there are several advantages, to
offset the extra maintenance:
Primary keys are often based on the content of the record. For
example, an employee ID is the primary key for the employee
table and uniquely identifies each employee. The employee
number field has a set format, such as XX-MMDDYY-1234. The
format has business meaning; the first part could identify the
employees department, the second could specify the employees
start date, and the third a unique number assigned to the
employee.
You can make an OID unique within a class, unique within a class
hierarchy, or unique across all classes.
If you make the OID unique only within a class, then you can have
12345 as the OID for a customer, an employee, an order, and any
other classes in the class diagram.
If you make OIDs unique to each class, you separately create OIDs
for every table that stores object data in the system. This has the
following implications.
The solutions for this are to reassign a matching OID for both
tables. This is costly because you must find one that is free in
both tables, use a database join table, which is less efficient, or
place a foreign key in one or both tables. This is wasteful if
there are only a few employees who are also customers.
If the OID is unique within the class hierarchy, then this problem is
alleviated. You do not need to reassign OIDs when changes occur
within the class hierarchy, such as a customer becoming an
employee.
If the OIDs are unique across all classes, you never have to change
them based on the object model. This provides the best results for
unique object identification, but can result in slower performance.
Single-row table
High/low
Single-row Table
In this method, use a single-row table that stores the next available
unique OID. Each time the OID is used and assigned to a new object,
the value in the table is incremented.
However, there are concurrency issues because each time you create an
object, you must lock the table and update the OID to ensure the OID
is not duplicated. This can significantly decrease performance because
the same table must be accessed every time a new object is created.
High/Low
With the high/low approach, the OID is a String composed of two
parts, a high and a low value. By appending the low value to the high,
you create a unique OID for each object.
The first part, or high value, comes from a single-row table that is
retrieved at the beginning of the session. However, the high-low
approach is different from the single-row table approach because
you do not have to retrieve the value from the table for each
object; you do it only once per user session. Each user retrieves a
different value, but during that session each user has the same
high value. All OIDs are based on the high value but differentiated
by an incremented low value.
High/Low
For example, assume a single-row table has the value 5000 and is
incremented by 1 at the beginning of each session. The application
begins the low values at 1 for each user and increments the low values
by 1 each time the user creates an object.
3. User B logs in and retrieves the next high value from the table,
5001.
5. When user A creates his or her first new object, such as a new
customer record, the OID is 5000 with 1 appended to produce the
OID 50001.
6. When user B creates new objects, they are assigned OIDs of 50011,
50012, and so on.
High/Low
Figure 3-1 illustrates each step in the example.
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
User B
5001
Object-Relational Mapping
Once you have determined how to uniquely identify each object, you
need to design the tables in your database, and decide how they will
relate to the classes in your application.
Note Objects, not classes, are stored in tables. The point at which you
actually save the objects in the database is implementation-dependent.
Object-Relational Mapping
To connect your object model with the database, complete these steps
before you begin defining your database.
Classes map to tables, but usually not directly. With a simple object
model, you can achieve a one-to-one mapping of object to table.
However, most object models are not simple.
Most object models have some inheritance, which causes the most
complexity when mapping classes to tables. There are three
fundamental approaches to mapping class inheritance to a relational
database; you can choose to follow any that meet your needs.
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
Advantages
Disadvantages
It takes longer to read and write to the tables, because you might
have to read from multiple tables to create one object.
abstractPerson
firstName
lastName
address
Customer Employee
customerOID employeeID
salutation SSN
Tables
Customer
firstName lastName address customerOID salutation
Employee
firstName lastName address employeeOID SSN
Note In Figure 3-3, each subclass has its own OID, because there is a
table for each. personOID was removed from the abstractPerson class
in the object model because there is no table in that class for this
approach to table design.
Advantages
Disadvantages
To modify a class, you must modify its table and the tables for any
subclasses.
Classes
abstractPerson
firstName
lastName
address
personOID
Customer Employee
salutation SSN
Table
Person
Advantages
Polymorphism is supported.
Disadvantages
Database tables can become extremely large. All fields are not
needed for all records; for example, the salutation field is required
only for customers, not employees.
When you add a new column, if it cannot have a null value, you
must update all records with a value for that column.
Many operations need to access the same table, which can reduce
performance.
Address PostalCode
addressOID addressOID
line1 postcodeOID
line2 postalCode
city
state
Table
Once you have mapped classes to tables, you need to map the class
attributes to columns in the tables. To do so, first review Table 3-1,
which shows the standard Java technology data types (Java types)
and the corresponding common SQL types.
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
Now that you have mapped the classes to tables, you need to map the
object relationships to tables in the database.
One-to-One Relationships
In a one-to-one relationship, the mapping is straightforward.
Sometimes it is only one-way; one table references another. Figure 3-6
illustrates the one-to-one relationship.
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
One-to-One Relationships
Figure 3-6 shows an example of the relationship between a Car class
and an Engine class, with a corresponding table for each. It is a one-to-
one relationship where 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
In a one-to-many relationship, for every one record in the first table
there are one or more records in the second table. The OID of the class
in the first table is added to the class of the second table.
Figure 3-7 shows tables for Order and OrderLine classes, which have a
one-to-many relationship from Order to OrderLine (each order can
have one or more line items; each line item can have only one order).
Classes
Order OrderLine
1 *
orderOID OLOID
isPrePaid orderOID
number quantity
dateReceived price
orderlines[ ]
Tables
Order
orderOID isPrePaid number dateReceived
OrderLine
OLOID orderOID quantity price
One-to-Many Relationships
In an order entry program, for example, there are many line items for
each order, so the orderOID is added to the OrderLine table. Add the
orderLineOID to the Order table because you need an array in the
Order table to handle all the orderLineOIDs that are associated with
the order.
Many-to-Many Relationships
Figure 3-8 shows the object model and tables with a many-to-many
relationship.
Classes
Address Customer
* *
addrOID custOID
line1 name
line2 address [ ]
city
state
postalCode
Tables
Address
Many-to-Many Relationships
Figure 3-8 show the relationship of Address to Customer; a Customer
can have many Addresses and an Address can belong to many
Customers. In this case, you can use a join table, such as
CustomerAddress, to link the class attributes.
Many-to-Many Relationships
Table 3-1 shows possible OID values in each of the three tables, with
the many-to-many relationships in boldface.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
What additional features would you like to have available for use in a
database application?
Objectives
Upon completion of this module, you should be able to:
Create transactions
4-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
4
Relevance
Exceptions
Overview
When a Java application communicates with the database, the
following elements are present:
The application
The database
When any part of this process goes wrong, the server must tell the
application. This is usually done using a SQLException, which
indicates any kind of error during a JDBC operation, or SQLWarning,
which indicates nonfatal problems. To address exceptions, use a
try/catch or throw construct.
Exceptions
SQLException
SQLException is different from other exceptions because it can have a
list of exception objects.
SQLException
Many errors can occur on the server, such as attempting to select
columns that do not exist. An error is returned for each incorrect
column name.
Exceptions
SQLWarning
SQLWarning is a subclass of SQLException that is returned for non-
fatal SQL states. SQLWarnings are not thrown; they are chained
together, and you can refer to them at any time. To retrieve them, call
the getWarnings method. You can call this method on several
different objects: anything that could generate a warning, such as a
Connection, all statement objects, and a ResultSet.
Metadata
Knowing the metadata for the information your application stores can
be very useful. The data is always available, which means you do not
need to generate it, only retrieve it.
Database metadata
Metadata
Database Metadata
Use the Connection.getMetaData method to retrieve database
metadata.
Metadata
Transactions
Overview
In database manipulation, a transaction is a logical group of work
consisting of one or more instructions. For example, the instructions
might be to enter a customer record, create a new order record, add a
line item to an order, and so on.
To drop the changes since the last commit, call the rollback
method. Calling the rollback method on the connection drops all
changes that have been made since the previous commit/rollback
and releases any database locks currently held by this
Connection. This method should be used only when auto-commit
has been disabled.
Basic Syntax
Syntax
2 conRefVar.setAutoCommit(false);
4 stmtRefVar.executeUpdate(sqlString);
5 conRefVar.transactionEndMethod;
Example
Transactions
Concurrency Control
Creating a transaction in the JDBC API is handled through the
Connection interface. For each connection, you can identify the
transaction isolation level, which determines what types of manipulation
are allowed. For example, it lets you control whether a row is reread if
it is altered after the first read.
Phantom reads When one transaction reads all rows that satisfy
a WHERE condition, a second transaction inserts a row that
satisfies that WHERE condition; the first transaction rereads for
the same condition, getting the additional row in the second read.
Transactions
Concurrency Control
To see the current isolation level, use the getTransactionIsolation
method.
Concurrency Control
TRANSACTION_READ_COMMITTED Prevents dirty reads.
Non-repeatable reads and phantom reads can occur.
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");
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Create transactions
Objectives
Upon completion of this module, you should be able to:
This module describes how to use the main features added in the latest
release of the JDBC API.
5-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
5
Relevance
Discussion Should a result set show or hide changes that have been
made to a database since it was retrieved? What advantages and
disadvantages are there for each approach?
JDBC 2.0 is a superset of JDBC 1.0. The classes and interfaces in the
java.sql package works for database drivers for either specification,
provided that you do not try to use the expanded JDBC 2.0
functionality with a JDBC 1.0 driver. Core API features in the JDBC 2.0
include:
Result set enhancements
Scrollability
Updatability
Enhancements to Statement, CallableStatement, and
PreparedStatement, for batch updates
Advanced JDBC data types to support SQL3
The JDBC 2.0 API includes two types of enhancements for result sets.
Scrollability
Scrollability
Scroll Settings
Forward-only
Scroll-insensitive
Scroll-sensitive
Scrollability
Scroll Settings
Scrollability
Scroll Settings
You can use the items listed in Table 5-1 to control scroll sensitivity
and other aspects of the result set. (These are also listed in the Java 2
Platform API Specification.)
Scrollability
Scroll Settings
Syntax
Statement stmtRefVar = conRefVar.createStatement
(int resultSetType, int resultSetConcurrency);
ResultSet resultsetRefVar = stmtRefVar.executeQuery
(sqlString);
Examples
This example uses none of the new features, and works in JDBC 1.0 or
2.0, using only 1.0 functionality.
1 Connection con = DriverManager.getConnection(
"jdbc:odbc:accounts");
2 Statement stmt = con.createStatement();
3 ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
Scrollability
Scroll Settings
Scrollability
Positioning
Scrollability
Positioning
You can use the methods in Table 5-2 to move and position within the
result set; these methods and others not listed here are included in the
API Specification.
Scrollability
Positioning
The JDBC 2.0 API also provides methods for you to determine where
you are within the ResultSet, shown in Table 5-3:
Updatability
Updatability allows you to manipulate data using the ResultSet scroll
cursor. This provides the capability of using one query to read
multiple rows from a database, then update rows in the database one
at a time. You can update, delete, and insert rows.
Updatability
To update the specific columns of a row, use the updateXXX methods,
which associate to the column type.
Updating a Row
Syntax
Example
The following code updates the first row of the result set.
1 rs.updateString(1, "100020");
2 rs.updateFloat("salary",60000.0f);
3 rs.updateRow();
You can specify the column number or column name when calling
updateXXX. The update performed on the result set is not applied to
the underlying database until you call updateRow. If you move the
cursor from the current row before calling updateRow, then the update
is discarded. In addition, you can call cancelRowUpdate to explicitly
cancel the updates, but you must call it before you make a call to
updateRow.
Updatability
Deleting a Row
Syntax
resultsetRefVar.deleteRow();
Example
The following example shows how to delete a row. The sixth row in
the result set is deleted from the database.
1 rs.absolute(6);
2 rs.deleteRow();
Syntax
Updatability
Example
The following example shows how to insert a new row into the
ResultSet and database.
1 rs.moveToInsertRow(); rs.updateString(1, "100050");
2 rs.updateFloat(2, 80000.0f);
3 rs.insertRow();
Updatability
Restrictions
The query selects all of the non-nullable columns in the table, and
all columns that do not have a default value.
The JDBC API cannot perform any operation during batch processing
that would produce a result set; if a result set is produced, an
exception is thrown. This ensures that you do not write code that can
generate multiple ResultSet objects during batch operations. Any
attempt to execute a ResultSet that produces a JDBC action during
batch operations results in an exception.
Statement
PreparedStatement
CallableStatement
Statement
The batch update feature allows a Statement object to submit a set of
heterogeneous update commands together as a single unit, or batch, to
the underlying DBMS. In the following example, all of the update
operations required to insert a new employee record into a company
database are submitted as a single batch.
Syntax
Statement stmtRefVar = conRefVar.createStatement();
stmtRefVar.addBatch(sqlString);
// submit a batch of update commands for execution
intArrayRefVar = stmtRefVar.executeBatch();
Statement
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
In JDBC 2.0, a Statement object can keep track of a list of commands
that can be submitted together for execution. When a statement is
created, its associated list of commands is empty. The
Statement.addBatch method adds an element (a SQL command) to
the calling statements list of commands.
Statement
The Statement.executeBatch method submits a batch of commands
to the underlying DBMS for execution. Commands are executed in the
order in which they were added to the batch. The executeBatch
method returns an array of update counts for the commands that were
executed. The array contains one entry for each command in the batch,
and the elements in the array are ordered according to the order in
which the commands were executed (which, again, is the same as the
order in which the commands were originally added to the batch).
Calling executeBatch closes the calling Statement objects current
result set if one is open. The statementss internal list of batch
commands for the rest of the statements is reset to empty once
executeBatch returns.
PreparedStatement
The batch update feature is used with prepared statements to associate
multiple sets of input parameter values with a single
PreparedStatement object. The sets of parameter values can then be
sent to the underlying DBMS engine for execution as one unit.
PreparedStatement
Syntax
PreparedStatement pstmtRefVar = conRefVar.prepareStatement
(sqlString);
pstmtRefVar.setXXXMethod(column, value);
// add other lines as necessary
pstmtRefVar.addBatch();
// submit the batch for execution
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
10 int[] updateCounts = stmt.executeBatch();
11 con.commit();
CallableStatement
The batch update feature works the same way with
CallableStatement objects as it does with PreparedStatement
objects. You can associate multiple sets of input parameter values with
a callable statement and send them to the DBMS together.
Overview
The data types commonly referred to as SQL3 types are the new data
types being 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 that represent
the mapping of these SQL3 data types into the Java programming
language. With these new interfaces, you can work with SQL3 data
types the same way you do other data types.
The new SQL3 data types give a relational database more flexibility in
what can be used as a type for a table column. For example, you can
now use a column to store the new type BLOB (binary large object),
which can store large amounts of data as raw bytes. A column can also
be of type CLOB (character large object), which can store large amounts
of data in character format. The new type ARRAY makes it possible to
use an array as a column value. The new SQL user-defined types,
structured types, and distinct types, can now be stored as column
values.
Overview
The following list includes the JDBC 2.0 interfaces that map the SQL3
types.
Arrays
The variable scores is a logical pointer to the SQL ARRAY object stored
in the table students in the row for student 2238.
Arrays
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()){
17 // Get the CLOB and use it to construct a BufferedReader
18 // (so that you can get the CLOBs 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 }
You can use SQL commands and the JDBC 1.0 and 2.0 API with Blob,
Clob, and Array objects just as if you were operating on the actual
object in the database. However, if you want to work with any of them
as an object in the Java programming language, you need to bring all
their data to the client, which is referred to as materializing the object.
Structured Types
A SQL structured type is similar to structured types in the Java
programming language in that it has members, called attributes, that
can be of any data type. In fact, an attribute can be another structured
type.
This example shows a simple definition creating a new SQL data type:
1 CREATE TYPE PLANE_POINT
2 (
3 X FLOAT,
4 Y FLOAT
5 )
Structured Types
Unlike Blob, Clob, and Array objects, a Struct object contains values
for each of the attributes in the SQL structured type and is not just a
logical pointer to the object in the database. For example, suppose that
a PLANE_POINT object is stored in column POINTS of table PRICES.
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 }
You might have noticed that Struct is the only type not to have a
getXXX and setXXX method with its name as XXX. You must use
getObject and setObject with Struct instances. This means that
when you retrieve a value using the method getObject, you get an
Object in the Java programming language that you must explicitly
cast to a Struct, as was done in the previous code example.
Distinct Types
The second SQL type that a user can define in a SQL CREATE TYPE
statement is a distinct type. A SQL distinct type is similar to a typedef
in C or C++ because it is a new type based on an existing type. The
following is an example of creating a distinct type.
CREATE TYPE MONEY AS NUMERIC(10, 2)
This definition creates the new type called MONEY, which is a number of
type NUMERIC that is always base 10 with two digits after the decimal
point. MONEY is now a data type in the schema in which it was defined,
and you can store instances of MONEY in a table that has a column of
type MONEY.
Distinct Types
A SQL distinct type is mapped to the type in the Java programming
language to which its underlying type would be mapped. For
example, NUMERIC maps to java.math.BigDecimal, so the type MONEY
maps to java.math.BigDecimal. To retrieve a MONEY object, use
ResultSet.getBigDecimal or CallableStatement.getBigDecimal;
to store a MONEY object, use PreparedStatement.setBigDecimal.
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
Explain how to use row sets to encapsulate rows for use with the
JavaBeans component model
6-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
6
Relevance
These features are optional and driver vendors are not required to
implement them. The features are included in the javax.sql package,
which is included in the Java 2 Platform, Enterprise Edition, and also
from the following site.
http://java.sun.com/products/jdbc/download.html
Connection pooling
Distributed transactions
Row sets
JNDI
Overview
The Java Naming and Directory Interface (JNDI) is a standard
extension to the Java platform, providing Java technology-enabled
applications with a uniform way for applications to find and access
remote services over the network. This allows you to connect
seamlessly to multiple enterprise naming and directory interfaces. The
JDBC 2.0 API provides support for JNDI.
The remote services you access using JNDI can be any enterprise
service, including a messaging service or application-specific service.
JNDI
JNDI Advantages
As described in Module 1, JDBC Overview, an application can
connect to a database using the JDBC driver manager. In this
approach, the JDBC driver that is used to create a database connection
must first be registered with the JDBC driver manager.
JNDI Advantages
This code demonstrates that a JDBC URL might be specific not only to
a particular vendors JDBC product, but also to a particular machine
name and port number on that machine. This can make the application
difficult to maintain because the computing environment changes.
One program associates the driver with a data source name you
choose.
This makes changing the driver easier, because you need to change it
in only one place.
JNDI
JDBC DataSource
A JDBC DataSource object is a Java programming language instance
of the javax.sql.DataSource interface. A data source object is a
factory for JDBC connections.
1 public interface DataSource {
2 Connection getConnection() throws SQLException;
3 Connection getConnection(String username, String password) throws
4 SQLException;
5 ...
6 }
JDBC DataSource
A class that implements the DataSource interface provides a set of
properties that must be given values so that a connection to a
particular data source can be made. These properties, which follow the
design pattern specified for JavaBeans model components, are usually
set when a data source object is used. Examples of data source
properties include the location of the database server, the name of the
database, the network protocol to use to communicate with the server,
and so on.
The JDBC 2.0 API specifies the following standard names for data
source properties:
JNDI
JDBC DataSource
A data source must support the description property. Support for the
other properties listed is not required because they might not be
needed by all data sources. However, if a data source needs to use one
of the properties listed in Table 6-1, it must use the standard property
name.
JDBC DataSource
For each property, you must be able to write to it and read it using
accessor and mutator methods.
For example, if sds denotes a data source object that supports the
serverName property, the following methods must be provided.
sds.setServerName("my_database_server");
String prop = sds.getServerName();
The accessor and mutator methods for a property are defined on the
implementation class and not in the DataSource interface. This creates
some separation between the management API for DataSource objects
and the API used by applications. Applications should not need to
access or change properties, but management tools can access them
using introspection.
A data source can contain a property that is not included on the list of
standard properties in Table 6-1. In this case, use a vendor-specific
name for the property.
The JDBC 2.0 API specifies a simple policy for assigning JNDI names
to data sources. All JDBC data sources should be registered in the jdbc
naming subcontext of a JNDI namespace, or in one of its child
subcontexts. The JDBC subcontext is the child of the root naming
context.
You can use JNDI to complete the first and second steps of the JDBC
process: registering the driver and connecting to the database.
JNDI
You can create, deploy, and manage a DataSource object within JNDI
separately from the Java applications that use it. This section describes
the use of DataSource objects.
Syntax
The first line of code in the example creates a data source object. The
SampleDataSource class implements the javax.sql.DataSource
interface. (A JDBC driver vendor supplies the SampleDataSource
class.) The next two lines initialize the data sources properties. Then, a
Java programming language object that references the initial JNDI
naming context is created by calling the InitialContext constructor,
which is provided by JNDI. System properties (not shown) are used to
tell JNDI the service provider to use.
JNDI
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");
Connection Pooling
Overview
A connection pool is a cache of database connections that is
maintained in memory, so that the connections can be reused.
Connection pooling can increase performance, especially when the
JDBC API is used in a middle-tier server environment, such as a Web
server capable of running Java applications.
The application does not register drivers; middle-tier code does the
registration. Connection pooling can simplify client code because
clients no longer have to deal with registering a driver.
Overview
Connection pooling has no impact on the code that you write. You
simply take advantage of a connection pool that has been
implemented in the driver, rather than writing code yourself.
Network
Application code
Client
(browser)
DataSource
ConnectionPoolDataSource Network
DBMS
JDBC driver
The three parts of this example are performed by the JDBC driver
vendor, the middle-tier server vendor, and the application developer.
Connection Pooling
Overview
To support connection pooling, a JDBC driver vendor must provide an
implementation of the javax.sql.ConnectionPoolDataSource
interface. This interface and the closely related
javax.sql.PooledConnection interface (not shown in Figure 6-1)
provide methodsor hooksthat enable a third party, such as a
middle-tier server vendor to implement connection pooling as a layer
on top of the JDBC API.
Connecting
A party, such as a middle-tier server vendor, who wants to implement
connection pooling should provide a data source class (a class that
implements the javax.sql.DataSource interface) to interact with
their particular connection pooling implementation. Application code
that you write can retrieve instances of this data source class from
JNDI and use it to obtain a database connection in the usual manner.
If you use connection pooling, the client does not have to register the
driver.
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
Overview
A distributed transaction is two or more tasks, on different entities (a
database, or other entity), that need to be committed as one
transaction. For example, moving money from an account in one bank
to an account in another is a distributed transaction.
Architecture
Figure 6-2 shows a simplified example of the basic components in a
distributed, three-tier application that uses the distributed transaction
features in the JDBC 2.0 API.
Network
Application code
Client
(browser)
DataSource
Transaction manager
XADataSource
Network DBMS
JDBC driver
Distributed Transactions
Architecture
On the client, a browser invokes a piece of application code that
executes in a middle-tier server environment. The middle-tier server
could be a Web server supporting Java technology, an Enterprise
JavaBeans server, or some other type of application server that
supports the Java programming language. The middle-tier application
code uses the JDBC API to access a pair of databases in the context of
a global (distributed) transaction.
Distributed Transactions
Implementation
To support distributed transactions, a JDBC driver vendor must
provide implementations of the javax.sql.XADataSource and
javax.sql.XAConnection interfaces. These interfaces are similar to
the ConnectionPoolDataSource and PooledConnection interfaces.
They provide the same hooks to enable connection pooling, and add
the ability to do distributed transactions.
Distributed Transactions
Implementation
Implementation
Transaction boundaries are controlled by the middle-tier server, so the
application code must not call the Connection.commit or
Connection.rollback methods. These methods throw a
SQLException if they are called.
Row Sets
Overview
A RowSet object encapsulates a set of rows that have been retrieved
from some tabular data source, such as results of a database query,
This makes it easy to send tabular data over a network. A RowSet
object must implement the javax.sql.RowSet interface, which adds
support to the JDBC API for the JavaBeans component model. The
RowSet interface inherits from the ResultSet interface.
The RowSet object provides a way to represent the rows so that they
can be used with the JavaBeans component model; a RowSet object is a
JavaBean that can be combined with other components in an
application. You can create row sets at design time and use them in
conjunction with other JavaBeans components in a visual JavaBeans
builder tool to construct an application
You also can use RowSet objects to provide scrollable result sets or
updatable result sets when the underlying JDBC driver does not
support them.
Overview
You can serialize a row set implementation.
Unlike statements and result sets, row sets are not tied to a specific
connection. A row set is affiliated with a connection only for the
duration of its use with a particular query.
Row Sets
A connected row set obtains a connection and keeps it open for as long
as the row set is in use.
Row Sets
Properties
This example uses a variable rset of type RowSet, and sets three
RowSet properties: data source name, transaction isolation, and
command. The data source name property is used by a RowSet to look
up a JDBC DataSource object in a JNDI naming service. (JDBC data
sources are the most common type of data source used by row sets.)
Properties
Row Sets
Events
Events
Cursor movement events indicate that the row sets cursor has
moved.
Row set change events indicate that the entire contents of a row set
changed. For example, this can happen when RowSet.execute is
called.
Events
Row Sets
Parameters
You can use the row set to execute queries, and pass values.
Row Sets
You iterate backward through the row set, positioning the cursor to a
specific row, and so on in the same way as a result set.
Row Sets
Command Execution
You can fill a row set with data by calling the RowSet.execute
method. This method uses the appropriate property values that have
been set to connect to a data source, and retrieve data. The exact
properties that you must set can vary between RowSet
implementations. Check the documentation for the particular row set
being used to find out what properties are required.
The current contents of the row set, if any, are lost when an execute
method is called.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Explain how to use row sets to encapsulate rows for use with the
JavaBeans component model
Objectives
Upon completion of this module, you should be able to:
7-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
7
Relevance
Figure 7-1 shows that you can use a CachedRowSet to provide Java
technology clients with access to tabular data in situations where it
would be inappropriate to use a JDBC driver directly in the client
due to resource limitations or security considerations.
RMI/CORBA
CachedRowSet
Tier 2
JDBC
DBMS Tier 3
Creating a CachedRowSet
Retrieving Data
Retrieving Data
Accessing Data
Modifying Data
A CachedRowSet object keeps track of both its original value and its
current value. The original value is set by methods
CachedRowSet.execute and populate. For example, when execute
is called, the original value is typically assigned the set of rows
returned by executing the row sets command. After calling execute
(or populate) the original value and the current value are the same.
UpdateRow does not affect the original value of the row or the
underlying values in the data source. Deleting and inserting rows is
done exactly as for ResultSets, so this is not shown in the example.
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);
10 crset.updateString(1, "Kara Stelter");
11 crset.updateFloat(2, 38000f);
12 crset.updateRow();
13 // update the original value and the database
14 crset.acceptChanges();
Miscellaneous Methods
Overview
The row set framework provides an extensible reader/writer facility
that allows you to customize data retrieval and updating, for complex
or specialized situations.The CachedRowSet class uses this facility.
Custom readers and writers are useful because they can enable a
RowSet to read its data from a regular file data source or from some
other non-SQL data source, such as a spreadsheet.
This approach separates where you get data from, and what you do
with it.
Overview
When an application calls the CachedRowSet.execute method:
Overview
Similarly, when the CachedRowSet.acceptChanges method is called,
the CachedRowSet invokes an object that implements the
RowSetWriter interface internally to handle the task of writing
changed rows back to the data source. The RowSetWriter.writeData
method is invoked by the row set to write any data that has been
changed. This method might detect a conflict with the underlying data
and signal this by returning a value of true to the caller.
Overview
Figure 7-2 outlines how readers and writers interact with a data source
and the CachedRowSet.
CachedRowSet
RowSetReader RowSetWriter
Data source*
RowSetReader
Refer to Appendix C of the JDBC 2.0 Standard Extension API (file name
jdbc20stdext.pdf), included in the specifications directory in your
lab files for this course, for an example of a RowSetReader
implementation.
The example in the appendix uses JDBC to read data from a SQL
database. A row set that supports the reader/writer paradigm should
implement the RowSetInternal interface and pass a reference to itself
when invoking the readData method.
The example readData method uses the calling row sets properties to
create a Connection to a data source. A PreparedStatement is
created using the command property and the PreparedStatement is
passed any properties that were set on the row set.
RowSetReader
The example is designed to be used with the CachedRowSet row set
implementation. You use the CachedRowSet.populate method to
read the rows from a ResultSet object into the row set. The example
assumes the caller is of type CachedRowSet. A SQLException is
thrown if anything goes wrong.
RowSetWriter
Refer to Appendix D of the JDBC 2.0 Standard Extension API (file name
jdbc20stdext.pdf), included in the specifications directory in your
lab files for this course, for an example of a RowSetWriter
implementation.
The writer calls the reader to create a Connection, and to find out if it
needs to reset itself. This might be necessary if new data has been read
since the command used to read the data might have changed. The
writer iterates through each row of the row set and updates the
underlying database when necessary.
Exercise objective Practice the concepts and tasks you have learned
in this module.
Tasks
Go to the SL330 directory on your computer and change to the lab files
directory. Open the directory for this module, then the directory for
this exercise, and read the readme file. Follow the instructions in that
file to complete this exercise.
Exercise Summary
Discussion Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
What considerations should you take into account when designing the
architecture of your Java application?
Objectives
Upon completion of this module, you should be able to:
8-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
8
Relevance
Client
Client
Data This component stores and allows access to the data, and is
typically in the third tier, the server.
Two-Tier Architecture
In the two-tier architecture, the application front end is in the first tier.
The database is in the second tier, the server tier. The Java application
or applet functioning as the presentation communicates directly with
the database. A users actions are translated in JDBC-based SQL
commands and are delivered to the database. The results of those
statements are sent back to the user.
You can store the database on another machine to which the user is
connected using a network. The network can be an intranet or the
Internet. This architecture enables the data to reside locally or
remotely.
If other users need a different presentation to the same data, you need
to develop only a new interface on the front end.
JDBC driver
DBMS
protocol
Database Data
server machine component DBMS
Note In the examples shown in this course, tiers are often shown on
separate machines; however, you can store tiers on the same machine.
Three-Tier Architecture
Three-Tier Architecture
You can implement all data validation, including business rules, in the
middle tier. The middle tier also can take over responsibility for
making connections to additional database servers.
RMI/CORBA,
HTTP
Application server
Server machine Business logic
component (Java technology)
JDBC driver
DBMS
protocol
Database Data
server machine component DBMS
For greater security, do not include SQL and the business logic on the
client.
N-Tier Architecture
First tier
Client
Caching control
Third tier
DBMS
First tier
Client
Third tier
DBMS
Choosing an Architecture
Two-Tier Architecture
Two-tier architecture is simple, straightforward, and typically suitable
for small applications. It is easier to implement if development
resources are significantly limited.
A limitation of the two-tier model is that the GUI and application logic
are tightly coupled, so the client program is responsible for all error
checking and all data is exposed on the network, which is not secure.
In addition, if database table schema changes on the server, you must
restructure the client code.
Two-Tier Architecture
Installing drivers requires more work.
For two-tier solutions, this means that you must install drivers on
every client machine, which is a potentially time-consuming task
for systems with many clients.
You can store business logic on either tier; however, when storing the
business logic on the server in the form of stored procedures, you lose
the platform- and DBMS-independence of JDBC.
Choosing an Architecture
The client might be much thinner than on the two-tier model and
consists essentially of the presentation, as well as control logic and
code that communicates with the middle tier. This might allow you to
use less powerful client machines. It also makes it easier to support
client machines of multiple platforms, because there is less code on
each.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this appendix, you should be able to:
A-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
A
References
Melton, Jim, Alan Simpson. 1993. Understanding the New SQL. San
Francisco: Morgan Kauffman Publishers.
The data must have a format that the DBMS and computer system
understands.
A database row (also called a record) contains the values for a specific
set of data stored in the database.
Table A-1 shows an example table named Customers with six columns
and three rows.
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
INSERT into CUSTOMER ("C8014", "Agata Omole","99 W Slade","Kalispell", "MT", "59901"
UPDATE CUSTOMER set Addr = "PO Box 709" where CustID = "C272"
DELETE from CUSTOMER where CustID = "C8007"
COMMIT WORK
Figure A-2 shows how, if one part of a transaction fails, the entire
transaction is reversed, or rolled back. The same beginning Customer
table is used.
BEGIN WORK
INSERT into CUSTOMER ("C8007", "Michael Wang","PO Box 42","Willmar", "MN", "56273"
INSERT into CUSTOMER ("C8014", "Agata Omole","99 W Slade","Kalispell", "MT", "59901"
UPDATE CUSTOMER set Addr = "PO Box 709" where CustID = "C272"
DELETE from CUSTOMER where CustID = "C8007"
DELETE FAILS
ROLLBACK
Pessimistic locking locks a row for the entire time the row is in
memory. This concurrency approach ensures that the row cannot be
updated by someone else at the same time you are updating. In
essence, there is no concurrency, because you are given exclusive
control of updating the row.
Optimistic locking locks a row only for the time that it is being
accessed in the database. When you read the row from the database, it
is locked during the read but released as soon as it is in memory. The
row is then locked again when you perform your update or delete.
This approach allows multiple people to work with the same row
simultaneously, but can cause people to overwrite each others
updates. Consider the following example.
Next, User A unmarks the checkbox so that it is set to no, and the
database row is updated.
At the same time User B is updating different fields and leaves the
Preferred Customer checkbox as yes.
When User B saves the changes and updates the row, it overwrites
the update from User A and sets the Preferred Customer checkbox
back to yes.
Before updating the row, reread the row and compare the
timestamp to the one in memory for that row.
At that point, you can include programming that will warn the user
that the record has changed since he or she first accessed it, and ask
Do you want to see the changes? or Do you want to make your
changes? Depending on the response, you would refresh the data or
perform your update.
Overview
Review the following if you are not familiar with SQL syntax.
There are five main categories of SQL; most statements fall into the
second category, Data Manipulation Language (DML):
You can read the syntax of SQL clauses like English commands. For
example, a SQL command could be to get me all of the fields in the
table named Employee Data, where the employee ID is 10223. If the
Employee Data table contained fields that held a name, employee ID,
date of hire, social security number, and current salary, you would
expect to receive a single employee record with these values.
Overview
This command is written using the following statement syntax:
SELECT * FROM employee_data WHERE employee_id = '10223'
SQL statements are not case sensitive, but the examples shown
highlight the keywords with capital letters.
SELECT Statement
Overview
The SELECT statement is the primary command used for data retrieval
from a SQL database. It supports the following:
Joins
ORDER BY clauses
SELECT Statement
Syntax
Examples
SELECT Statement
Examples
To remove any duplicate rows, you can use the DISTINCT operator:
SELECT DISTINCT first_name, last_name FROM emp_details
WHERE dept = 'finance'
ORDER BY last_name, first_name DESC
Joins
SELECT Statement
Joins
Note You must qualify all column names with a table name. SQL
does not support the concept of uniquely named columns spanning
multiple tables. You must qualify every column name as soon as you
access more than one table in a single SELECT.
INSERT Statement
Note Unlike ANSI SQL, you cannot nest a SELECT statement within
an INSERT statement. That is, you cannot insert the data returned by a
SELECT statement.
The INSERT statement adds new SQL records to a table. You must
specify the names of the fields into which the data is to be inserted.
You cannot specify the values without the field name; the server does
not insert the data into the correct fields by default.
For example:
INSERT INTO emp_details ( first_name, last_name, dept, salary)
VALUES ('Joe', 'Mays', 'I.T.S.','12345')
DELETE Statement
The DELETE statement removes records from a SQL table. The syntax
for DELETE is:
DELETE FROM table_name
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
DELETE FROM emp_details WHERE emp_id = '12345'
UPDATE Statement
The UPDATE statement is the SQL mechanism for changing the contents
of a SQL record. To change a particular record, you must identify what
record from the table you want to change. The UPDATE statement
cannot use a column name as a value. You can use only literal values
as an UPDATE value. The syntax for UPDATE is:
UPDATE table_name SET column=value [ , column=value ]...
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
UPDATE emp_details SET salary=30000 WHERE emp_id = '1234'
Objectives
Upon completion of this appendix, you should be able to:
This appendix defines SQLJ, and describes how to use SQLJ to connect
a Java application to a relational database.
B-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
B
References
SQLJ is for static SQL, as opposed to the JDBC API, which is for static
or dynamic SQ:; you can use both in your programs. SQLJ uses JDBC
calls, so you can combine the two in the same program. You can
initialize a JDBC connection with a SQLJ connection context, or a SQLJ
connection with a JDBC connection context.
You still need a JDBC driver to connect to the database using SQLJ.
While you need the driver for both the JDBC API and SQLJ, using
SQLJ is sometimes a better choice because its source programs are
smaller and it does compile-time type checking. You can verify queries
against the database before actually running the application.
You also can create a JDBC ResultSet from a SQLJ iterator, covered
later in this module in the Executing the Query and Reviewing the
Result Set Using Iterator Objects. section. Therefore, the dynamic SQL
API for SQLJ is the JDBC API.
Java application*
SQLJ Runtime
JDBC API
The SQLJ Runtime is a thin layer of 100% Pure Java code that is
located above the JDBC driver and is used to communicate with your
program. Programs translated by SQLJ can access any database with a
JDBC driver and a compliant SQLJ Runtime. This allows programs to
be portable across platforms and databases.
SQLJ program files contain the static SQL calls to connect to the
relational database, and are indicated with a .sqlj extension.
sqlj filename.sqlj
Step 1
javac filename.java
Step 2
Code Example
To see how the .sqlj file looks before and after compiling, open the
lab files directory for this course. Locate the directory for SQLJ, and
open the files named SqljDemo.sqlj and SqljDemo.java.
The steps for using SQLJ to connect to and review data from a
database are similar to the six main steps that you follow to use the
JDBC API, and shown in Table B-1.
Syntax
DefaultContext ctxtVariable;
ctxtVariable = new DefaultContext (JDBCConnection);
DefaultContext.setDefaultContext (ctxtVariable);
Example
31 DriverManager.registerDriver((Driver)driverClass.newInstance());
32 conn = DriverManager.getConnection (dburl, uid, pwd);
33 } catch (Exception e) {
34 System.err.println( "Could not establish the JDBC connection:") ;
35 System.err.println(e); System.exit(1);
36 }
37 return conn;
38 }
39
40 /**
41 Returns the currently installed SQLJ default context.
42 If the current default context is null, a new default context
43 instance is set up using a connection obtained from
44 <code>getConnection()</code>.
45 **/
46 static public DefaultContext initContext()
47 {
48 DefaultContext ctx = DefaultContext.getDefaultContext();
49 if (ctx == null) {
50 try {
51 ctx = new DefaultContext(newConnection());
52 } catch (SQLException e) {
53 System.out.println("Error: could not get a default context");
54 System.err.println(e) ; System.exit(1);
55 }
56 DefaultContext.setDefaultContext(ctx);
57 }
58 return ctx;
59 }
60 }
SQLJ Clauses
Static SQL appears in a SQLJ program as a SQLJ clause. A SQLJ clause
begins with the token #sql and then contains a SQL statement that is
enclosed in curly braces. A SQLJ clause can be any place in the
program that a Java programming language statement might appear.
Syntax
#sql {SQLString};
Example
The following SQLJ clause selects the first and last name from the
Customer table for a given customer ID:
1 String firstName;
2 String lastName;
3 int customerID;
4 #sql{SELECT fname, lname INTO :firstName, :lastName FROM Customer
WHERE custID = :customerID};
Host Variables
Host variables are used to pass the input and output of SQL
statements. A host variable is a Java programming language variable,
parameter, or field that is embedded in a SQL statement prefixed by a
colon.
Syntax
Example
String firstName
Syntax
:variable
Example
Example
Example
1 SalesRecs sales;
To see a complete .sqlj file and the resulting .java file using
iterators, open the lab files directory for this course. Locate the
directory for SQLJ, and open the files named IterDemo1.sqlj and
IterDemo1.java.
ANSI
American National Standards Institute.
Business rules
Rules governing what operations are permitted on application
data and what constraints apply to those operations. These
rules generally vary depending on the business requirements of
the application being designed.
Client/server
An application architecture where functionality is divided
between service requestors (clients) and service providers
(servers). Generally, the client part of the architecture allows the
user to interact with the system and the server provides the
ability to store and manipulate application data or resources.
Client/server architectures tend to be very flexible, allowing
one or more clients to use resources from one or more servers.
Column
A description of a data element that resides in a relational table.
The description of a column is referred to as its metadata, and
consists of the elements name, data type, and special attributes,
such as being a non-null field.
Commit
The act of finalizing a transaction (set of operations) on a
database.
Concurrency
In databases, the attempt by several users to access the same
database structure. In relational databases, this means accessing
the same table.
Glossary-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Connection pool
A managed set of database connections. A connection pool can
be used in a distributed system and can provide performance
improvements for the application.
Database
A shared collection of logically related data and a description of
the data elements.
Database Management System (DBMS)
A software system allowing users to define, create, and
maintain databases and the data stored within. A DMBS also
provides controlled access to a database.
Dynamic SQL
An approach to generating SQL queries where the SQL
command is first stored in a local variable, then is passed to the
database for execution. This provides the application with the
flexibility to change the SQL instruction and execute the
command on the fly. In the Java programming language, JDBC
provides support for dynamic SQL.
Embedded SQL
Hard-coded SQL instructions directly written into a program. In
the Java programming language, SQLJ provides this capability.
Foreign key
In relational databases, a column that matches database rows in
one table to zero or more rows within another table. This is
used to represent a one-to-many relationship for tables in
databases.
ISO
International Standards Organization.
Java 2 SDK
The latest release of a set of program modules, applications, and
class files used to develop and run applications written in the
Java programming language (previously referred to as the
JDK).
Java Naming and Directory Interface (JNDI)
An extension to the Java platform that provides applications
with a unified interface to multiple naming and directory
services in an enterprise environment.
Glossary Glossary-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Object Oriented Database Management System (OODBMS)
A database management system that supports storage and
maintenance of a persistent and sharable collection of objects.
Object Relational Database Management System (ORDBMS)
A hybrid between an RDBMS and an OODBMS. An object
relational database management system is a relational database
management system that provides extended support for object
storage and retrieval. The SQL3 standard defines the extensions
to SQL required to support this model.
Optimistic Locking
A locking strategy, where transactions are allowed to run until
completion. At commit time, a check is made to see if a conflict
occurred. In the case of conflict, the transaction that caused the
conflict is rolled back and restarted.
Pessimistic Locking
A locking strategy where one or more rows in a database table
are locked (unavailable) for the duration of a specific
transaction. During this time, other transactions cannot perform
operations on the locked row or rows.
Primary key
A column in a relational database table used to uniquely
identify records within that table.
Query
In SQL, a request, command, or instruction for the database.
Relational Database Management System (RDBMS)
A kind of database management system that stores its data in
tables consisting of rows and columns. A column represents one
data type within the table. A row is a database record, a set of
values for the given table. RDBMS systems allow data to be
freely organized between the storage tables, providing a flexible
strategy for dynamically relating data elements based on the
needs of an application. Most RDBMS systems define some
form of SQL to provide the capability for clients to perform
operations on the relational database.
Rollback
In a transaction, the act of reversing the previous operations to
restore a database to its previous state. This is also called
backing out of a transaction.
Glossary Glossary-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, October 1999, Revision A.1
Transaction
In database manipulation, a logical group of work consisting of
one or more instructions. For a transaction to execute
successfully, all of its instructions must be successfully executed
for the database. If there is an error any time during transaction
execution, the previous operations must be reversed. This is
referred to as backing out or performing a rollback on a
transaction.
Two-tier
An architecture for client/server systems. Normally, a client
interface, located on a users computer system, interacts with a
database management system on another machine. The
database management system generally services requests from
many clients.
Please
Recycle