Top Banner
java.sql (Java Platform SE 6) Overview Package Class Use Tree Deprecated Index Help Java™ Platform Standard Ed. 6 PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES All Classes Package java.sql Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java TM programming language. See: Description Interface Summary Array The mapping in the Java programming language for the SQL type ARRAY. Blob The representation (mapping) in the Java TM programming language of an SQL BLOB value. CallableStatement The interface used to execute SQL stored procedures. Clob The mapping in the Java TM programming language for the SQL CLOB type. Connection A connection (session) with a specific database. DatabaseMetaData Comprehensive information about the database as a whole. Driver The interface that every driver class must implement. NClob The mapping in the Java TM programming language for the SQL NCLOB type. ParameterMetaData An object that can be used to get information about the types and properties for each parameter marker in a PreparedStatement object. PreparedStatement An object that represents a precompiled SQL statement. Ref The mapping in the Java programming language of an SQL REF value, which is a reference to an SQL structured type value in the database. ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database. ResultSetMetaData An object that can be used to get information about the types and properties of the columns in a ResultSet object. http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (1 of 9)8/18/2008 2:54:41 PM
28

Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Oct 06, 2018

Download

Documents

phungkhanh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

Overview Package Class Use Tree Deprecated Index Help Java™ Platform Standard Ed. 6

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES All Classes

Package java.sql

Provides the API for accessing and processing data stored in a data source (usually a relational database)

using the JavaTM programming language.

See: Description

Interface SummaryArray The mapping in the Java programming language for the SQL type ARRAY.

Blob The representation (mapping) in the JavaTM programming language of an SQL BLOB value.

CallableStatement The interface used to execute SQL stored procedures.

Clob The mapping in the JavaTM programming language for the SQL CLOB type.

Connection A connection (session) with a specific database.

DatabaseMetaData Comprehensive information about the database as a whole.

Driver The interface that every driver class must implement.

NClob The mapping in the JavaTM programming language for the SQL NCLOB type.

ParameterMetaData An object that can be used to get information about the types and properties for each parameter marker in a PreparedStatement object.

PreparedStatement An object that represents a precompiled SQL statement.

Ref The mapping in the Java programming language of an SQL REF value, which is a reference to an SQL structured type value in the database.

ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

ResultSetMetaData An object that can be used to get information about the types and properties of the columns in a ResultSet object.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (1 of 9)8/18/2008 2:54:41 PM

Page 2: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

RowId The representation (mapping) in the Java programming language of an SQL ROWID value.

SavepointThe representation of a savepoint, which is a point within the current transaction that can be referenced from the Connection.rollback method.

SQLData The interface used for the custom mapping of an SQL user-defined type (UDT) to a class in the Java programming language.

SQLInput An input stream that contains a stream of values representing an instance of an SQL structured type or an SQL distinct type.

SQLOutput The output stream for writing the attributes of a user-defined type back to the database.

SQLXML The mapping in the JavaTM programming language for the SQL XML type.

Statement The object used for executing a static SQL statement and returning the results it produces.

Struct The standard mapping in the Java programming language for an SQL structured type.

Wrapper Interface for JDBC classes which provide the ability to retrieve the delegate instance when the instance in question is in fact a proxy class.

Class Summary

Date A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value.

DriverManagerThe basic service for managing a set of JDBC drivers. NOTE: The DataSource interface, new in the JDBC 2.0 API, provides another way to connect to a data source.

DriverPropertyInfo Driver properties for making a connection.

SQLPermissionThe permission for which the SecurityManager will check when code that is running in an applet calls the DriverManager.setLogWriter method or the DriverManager.setLogStream (deprecated) method.

Time A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL TIME value.

Timestamp A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (2 of 9)8/18/2008 2:54:41 PM

Page 3: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

Types The class that defines the constants that are used to identify generic SQL types, called JDBC types.

Enum Summary

ClientInfoStatus Enumeration for status of the reason that a property could not be set via a call to Connection.setClientInfo

RowIdLifetime Enumeration for RowId life-time values.

Exception Summary

BatchUpdateExceptionThe subclass of SQLException thrown when an error occurs during a batch update operation.

DataTruncation

An exception thrown as a DataTruncation exception (on writes) or reported as a DataTruncation warning (on reads) when a data values is unexpectedly truncated for reasons other than its having execeeded MaxFieldSize.

SQLClientInfoExceptionThe subclass of SQLException is thrown when one or more client info properties could not be set on a Connection.

SQLDataExceptionThe subclass of SQLException thrown when the SQLState class value is '22'.

SQLException An exception that provides information on a database access error or other errors.

SQLFeatureNotSupportedExceptionThe subclass of SQLException thrown when the SQLState class value is '0A' ( the value is 'zero' A).

SQLIntegrityConstraintViolationExceptionThe subclass of SQLException thrown when the SQLState class value is '23'.

SQLInvalidAuthorizationSpecExceptionThe subclass of SQLException thrown when the SQLState class value is '28'.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (3 of 9)8/18/2008 2:54:41 PM

Page 4: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

SQLNonTransientConnectionException

The subclass of SQLException thrown for the SQLState class value '08', representing that the connection operation that failed will not succeed when the operation is retried without the cause of the failure being corrected.

SQLNonTransientException

The subclass of SQLException thrown when an instance where a retry of the same operation would fail unless the cause of the SQLException is corrected.

SQLRecoverableException

The subclass of SQLException thrown in situations where a previously failed operation might be able to succeed if the application performs some recovery steps and retries the entire transaction or in the case of a distributed transaction, the transaction branch.

SQLSyntaxErrorExceptionThe subclass of SQLException thrown when the SQLState class value is '42'.

SQLTimeoutExceptionThe subclass of SQLException thrown when the timeout specified by Statement has expired.

SQLTransactionRollbackExceptionThe subclass of SQLException thrown when the SQLState class value is '40'.

SQLTransientConnectionException

The subclass of SQLException for the SQLState class value '08', representing that the connection operation that failed might be able to succeed when the operation is retried without any application-level changes.

SQLTransientException

The subclass of SQLException is thrown in situations where a previoulsy failed operation might be able to succeed when the operation is retried without any intervention by application-level functionality.

SQLWarning An exception that provides information on database access warnings.

Package java.sql Description

Provides the API for accessing and processing data stored in a data source (usually a relational database)

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (4 of 9)8/18/2008 2:54:41 PM

Page 5: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

using the JavaTM programming language. This API includes a framework whereby different drivers can

be installed dynamically to access different data sources. Although the JDBCTM API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. The reader/writer facility, available through the javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, flat file, or any other tabular data source.

What the JDBCTM 4.0 API Includes

The JDBCTM 4.0 API includes both the java.sql package, referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional Package API. This complete JDBC API is

included in the JavaTM Standard Edition (Java SETM), version 6. The javax.sql package extends the functionality of the JDBC API from a client-side API to a server-side API, and it is an essential part of

the JavaTM Enterprise Edition (Java EETM) technology.

Versions

The JDBC 4.0 API incorporates all of the previous JDBC API versions:

● The JDBC 3.0 API ● The JDBC 2.1 core API ● The JDBC 2.0 Optional Package API

(Note that the JDBC 2.1 core API and the JDBC 2.0 Optional Package API together are referred to as the JDBC 2.0 API.)

● The JDBC 1.2 API ● The JDBC 1.0 API

Classes, interfaces, methods, fields, constructors, and exceptions have the following "since" tags that indicate when they were introduced into the Java platform. When these "since" tags are used in

JavadocTM comments for the JDBC API, they indicate the following:

● Since 1.6 -- new in the JDBC 4.0 API and part of the Java SE platform, version 6 ● Since 1.4 -- new in the JDBC 3.0 API and part of the J2SE platform, version 1.4 ● Since 1.2 -- new in the JDBC 2.0 API and part of the J2SE platform, version 1.2

● Since 1.1 or no "since" tag -- in the original JDBC 1.0 API and part of the JDKTM, version 1.1

NOTE: Many of the new features are optional; consequently, there is some variation in drivers and the features they support. Always check your driver's documentation to see whether it supports a feature before you try to use it.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (5 of 9)8/18/2008 2:54:41 PM

Page 6: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

NOTE: The class SQLPermission was added in the JavaTM 2 SDK, Standard Edition, version 1.3 release. This class is used to prevent unauthorized access to the logging stream associated with the DriverManager, which may contain information such as table names, column data, and so on.

What the java.sql Package Contains

The java.sql package contains API for the following:

● Making a connection with a database via the DriverManager facility ❍ DriverManager class -- makes a connection with a driver ❍ SQLPermission class -- provides permission when code running within a Security

Manager, such as an applet, attempts to set up a logging stream through the DriverManager

❍ Driver interface -- provides the API for registering and connecting drivers based on JDBC technology ("JDBC drivers"); generally used only by the DriverManager class

❍ DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the general user

● Sending SQL statements to a database ❍ Statement -- used to send basic SQL statements ❍ PreparedStatement -- used to send prepared statements or basic SQL statements

(derived from Statement) ❍ CallableStatement -- used to call database stored procedures (derived from PreparedStatement)

❍ Connection interface -- provides methods for creating statements and managing connections and their properties

❍ Savepoint -- provides savepoints in a transaction ● Retrieving and updating the results of a query

❍ ResultSet interface ● Standard mappings for SQL types to classes and interfaces in the Java programming language

❍ Array interface -- mapping for SQL ARRAY ❍ Blob interface -- mapping for SQL BLOB ❍ Clob interface -- mapping for SQL CLOB ❍ Date class -- mapping for SQL DATE ❍ NClob interface -- mapping for SQL NCLOB ❍ Ref interface -- mapping for SQL REF ❍ RowId interface -- mapping for SQL ROWID ❍ Struct interface -- mapping for SQL STRUCT ❍ SQLXML interface -- mapping for SQL XML ❍ Time class -- mapping for SQL TIME ❍ Timestamp class -- mapping for SQL TIMESTAMP ❍ Types class -- provides constants for SQL types

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (6 of 9)8/18/2008 2:54:41 PM

Page 7: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

● Custom mapping an SQL user-defined type (UDT) to a class in the Java programming language ❍ SQLData interface -- specifies the mapping of a UDT to an instance of this class ❍ SQLInput interface -- provides methods for reading UDT attributes from a stream ❍ SQLOutput interface -- provides methods for writing UDT attributes back to a stream

● Metadata ❍ DatabaseMetaData interface -- provides information about the database ❍ ResultSetMetaData interface -- provides information about the columns of a ResultSet object

❍ ParameterMetaData interface -- provides information about the parameters to PreparedStatement commands

● Exceptions ❍ SQLException -- thrown by most methods when there is a problem accessing data and

by some methods for other reasons ❍ SQLWarning -- thrown to indicate a warning ❍ DataTruncation -- thrown to indicate that data may have been truncated ❍ BatchUpdateException -- thrown to indicate that not all commands in a batch

update executed successfully

java.sql and javax.sql Features Introduced in the JDBC 4.0 API

● auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName

● National Character Set support added ● Support added for the SQL:2003 XML data type ● SQLException enhancements -- Added support for cause chaining; New SQLExceptions added

for common SQLState class value codes ● Enhanced Blob/Clob functionality -- Support provided to create and free a Blob/Clob instance as

well as additional methods added to improve accessiblity ● Support added for accessing a SQL ROWID ● Support added to allow a JDBC application to access an instance of a JDBC resource that has

been wrapped by a vendor, usually in an application server or connection pooling environment. ● Availability to be notfied when a PreparedStatement that is associated with a PooledConnection has been closed or the driver determines is invalid

java.sql and javax.sql Features Introduced in the JDBC 3.0 API

● Pooled statements -- reuse of statements associated with a pooled connection ● Savepoints -- allow a transaction to be rolled back to a designated savepoint ● Properties defined for ConnectionPoolDataSource -- specify how connections are to be

pooled ● Metadata for parameters of a PreparedStatement object ● Ability to retrieve values from automatically generated columns

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (7 of 9)8/18/2008 2:54:41 PM

Page 8: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

● Ability to have multiple ResultSet objects returned from CallableStatement objects open at the same time

● Ability to identify parameters to CallableStatement objects by name as well as by index ● ResultSet holdability -- ability to specify whether cursors should be held open or closed at the

end of a transaction ● Ability to retrieve and update the SQL structured type instance that a Ref object references ● Ability to programmatically update BLOB, CLOB, ARRAY, and REF values. ● Addition of the java.sql.Types.DATALINK data type -- allows JDBC drivers access to

objects stored outside a data source ● Addition of metadata for retrieving SQL type hierarchies

java.sql Features Introduced in the JDBC 2.1 Core API

● Scrollable result sets--using new methods in the ResultSet interface that allow the cursor to be moved to a particular row or to a position relative to its current position

● Batch updates ● Programmatic updates--using ResultSet updater methods ● New data types--interfaces mapping the SQL3 data types ● Custom mapping of user-defined types (UDTs) ● Miscellaneous features, including performance hints, the use of character streams, full precision

for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.

javax.sql Features Introduced in the JDBC 2.0 Optional Package API

● The DataSource interface as a means of making a connection. The Java Naming and Directory

InterfaceTM (JNDI) is used for registering a DataSource object with a naming service and also for retrieving it.

● Pooled connections -- allowing connections to be used and reused ● Distributed transactions -- allowing a transaction to span diverse DBMS servers ● RowSet technology -- providing a convenient means of handling and passing data

Custom Mapping of UDTs

A user-defined type (UDT) defined in SQL can be mapped to a class in the Java programming language. An SQL structured type or an SQL DISTINCT type are the UDTs that may be custom mapped. The following three steps set up a custom mapping:

1. Defining the SQL structured type or DISTINCT type in SQL 2. Defining the class in the Java programming language to which the SQL UDT will be mapped.

This class must implement the SQLData interface.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (8 of 9)8/18/2008 2:54:41 PM

Page 9: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

java.sql (Java Platform SE 6)

3. Making an entry in a Connection object's type map that contains two things: ❍ the fully-qualified SQL name of the UDT ❍ the Class object for the class that implements the SQLData interface

When these are in place for a UDT, calling the methods ResultSet.getObject or CallableStatement.getObject on that UDT will automatically retrieve the custom mapping for it. Also, the PreparedStatement.setObject method will automatically map the object back to its SQL type to store it in the data source.

Package Specification

● Specification of the JDBC 4.0 API

Related Documentation

● Getting Started--overviews of the major interfaces

● Chapters on the JDBC API--from the online version of The Java Tutorial Continued

● JDBCTMAPI Tutorial and Reference, Third Edition-- a complete reference and tutorial for the JDBC 3.0 API

Since: 1.1

Overview Package Class Use Tree Deprecated Index Help Java™ Platform Standard Ed. 6

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES All Classes

Submit a bug or feature For further API reference and developer documentation, see Java SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.

Copyright 2006 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. Also see the

documentation redistribution policy.

http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html (9 of 9)8/18/2008 2:54:41 PM

Page 10: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

Overview Package Class Use Tree Deprecated Index Help Java™ Platform Standard Ed. 6

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES All Classes

Package javax.sql

Provides the API for server side data source access and processing from the JavaTM programming language.

See: Description

Interface Summary

CommonDataSourceInterface that defines the methods which are common between DataSource, XADataSource and ConnectionPoolDataSource.

ConnectionEventListener An object that registers to be notified of events generated by a PooledConnection object.

ConnectionPoolDataSource A factory for PooledConnection objects.

DataSource A factory for connections to the physical data source that this DataSource object represents.

PooledConnection An object that provides hooks for connection pool management.

RowSet The interface that adds support to the JDBC API for the JavaBeansTM component model.

RowSetInternal The interface that a RowSet object implements in order to present itself to a RowSetReader or RowSetWriter object.

RowSetListenerAn interface that must be implemented by a component that wants to be notified when a significant event happens in the life of a RowSet object.

RowSetMetaData An object that contains information about the columns in a RowSet object.

RowSetReader The facility that a disconnected RowSet object calls on to populate itself with rows of data.

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (1 of 7)8/18/2008 12:30:49 PM

Page 11: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

RowSetWriter An object that implements the RowSetWriter interface, called a writer.

StatementEventListener An object that registers to be notified of events that occur on PreparedStatements that are in the Statement pool.

XAConnection An object that provides support for distributed transactions.

XADataSource A factory for XAConnection objects that is used internally.

Class Summary

ConnectionEvent An Event object that provides information about the source of a connection-related event.

RowSetEvent An Event object generated when an event occurs to a RowSet object.

StatementEvent A StatementEvent is sent to all StatementEventListeners which were registered with a PooledConnection.

Package javax.sql Description

Provides the API for server side data source access and processing from the JavaTM programming language. This package supplements the java.sql package and, as of the version 1.4 release, is

included in the Java Platform, Standard Edition (Java SETM). It remains an essential part of the Java

Platform, Enterprise Edition (Java EETM).

The javax.sql package provides for the following:

1. The DataSource interface as an alternative to the DriverManager for establishing a connection with a data source

2. Connection pooling and Statement pooling 3. Distributed transactions 4. Rowsets

Applications use the DataSource and RowSet APIs directly, but the connection pooling and distributed transaction APIs are used internally by the middle-tier infrastructure.

Using a DataSource Object to Make a Connection

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (2 of 7)8/18/2008 12:30:49 PM

Page 12: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

The javax.sql package provides the preferred way to make a connection with a data source. The DriverManager class, the original mechanism, is still valid, and code using it will continue to run. However, the newer DataSource mechanism is preferred because it offers many advantages over the DriverManager mechanism.

These are the main advantages of using a DataSource object to make a connection:

● Changes can be made to a data source's properties, which means that it is not necessary to make changes in application code when something about the data source or driver changes.

● Connection and Statement pooling and distributed transactions are available through a DataSource object that is implemented to work with the middle-tier infrastructure. Connections made through the DriverManager do not have connection and statement pooling or distributed transaction capabilities.

Driver vendors provide DataSource implementations. A particular DataSource object represents a particular physical data source, and each connection the DataSource object creates is a connection to that physical data source.

A logical name for the data source is registered with a naming service that uses the Java Naming and

Directory InterfaceTM (JNDI) API, usually by a system administrator or someone performing the duties of a system administrator. An application can retrieve the DataSource object it wants by doing a lookup on the logical name that has been registered for it. The application can then use the DataSource object to create a connection to the physical data source it represents.

A DataSource object can be implemented to work with the middle tier infrastructure so that the connections it produces will be pooled for reuse. An application that uses such a DataSource implementation will automatically get a connection that participates in connection pooling. A DataSource object can also be implemented to work with the middle tier infrastructure so that the connections it produces can be used for distributed transactions without any special coding.

Connection Pooling and Statement Pooling

Connections made via a DataSource object that is implemented to work with a middle tier connection pool manager will participate in connection pooling. This can improve performance dramatically because creating new connections is very expensive. Connection pooling allows a connection to be used and reused, thus cutting down substantially on the number of new connections that need to be created.

Connection pooling is totally transparent. It is done automatically in the middle tier of a Java EE configuration, so from an application's viewpoint, no change in code is required. An application simply uses the DataSource.getConnection method to get the pooled connection and uses it the same way it uses any Connection object.

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (3 of 7)8/18/2008 12:30:49 PM

Page 13: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

The classes and interfaces used for connection pooling are:

● ConnectionPoolDataSource ● PooledConnection ● ConnectionEvent ● ConnectionEventListener ● StatementEvent ● StatementEventListener

The connection pool manager, a facility in the middle tier of a three-tier architecture, uses these classes and interfaces behind the scenes. When a ConnectionPoolDataSource object is called on to create a PooledConnection object, the connection pool manager will register as a ConnectionEventListener object with the new PooledConnection object. When the connection is closed or there is an error, the connection pool manager (being a listener) gets a notification that includes a ConnectionEvent object.

If the connection pool manager supports Statement pooling, for PreparedStatements, which can be determined by invoking the method DatabaseMetaData.supportsStatementPooling, the connection pool manager will register as a StatementEventListener object with the new PooledConnection object. When the PreparedStatement is closed or there is an error, the connection pool manager (being a listener) gets a notification that includes a StatementEvent object.

Distributed Transactions

As with pooled connections, connections made via a DataSource object that is implemented to work with the middle tier infrastructure may participate in distributed transactions. This gives an application the ability to involve data sources on multiple servers in a single transaction.

The classes and interfaces used for distributed transactions are:

● XADataSource ● XAConnection

These interfaces are used by the transaction manager; an application does not use them directly.

The XAConnection interface is derived from the PooledConnection interface, so what applies to a pooled connection also applies to a connection that is part of a distributed transaction. A transaction manager in the middle tier handles everything transparently. The only change in application code is that an application cannot do anything that would interfere with the transaction manager's handling of the transaction. Specifically, an application cannot call the methods Connection.commit or

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (4 of 7)8/18/2008 12:30:49 PM

Page 14: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

Connection.rollback, and it cannot set the connection to be in auto-commit mode (that is, it cannot call Connection.setAutoCommit(true)).

An application does not need to do anything special to participate in a distributed transaction. It simply creates connections to the data sources it wants to use via the DataSource.getConnection method, just as it normally does. The transaction manager manages the transaction behind the scenes. The XADataSource interface creates XAConnection objects, and each XAConnection object creates an XAResource object that the transaction manager uses to manage the connection.

Rowsets

The RowSet interface works with various other classes and interfaces behind the scenes. These can be grouped into three categories.

1. Event Notification ❍ RowSetListener

A RowSet object is a JavaBeansTM component because it has properties and participates in the JavaBeans event notification mechanism. The RowSetListener interface is implemented by a component that wants to be notified about events that occur to a particular RowSet object. Such a component registers itself as a listener with a rowset via the RowSet.addRowSetListener method.

When the RowSet object changes one of its rows, changes all of it rows, or moves its cursor, it also notifies each listener that is registered with it. The listener reacts by carrying out its implementation of the notification method called on it.

❍ RowSetEvent As part of its internal notification process, a RowSet object creates an instance of RowSetEvent and passes it to the listener. The listener can use this RowSetEvent object to find out which rowset had the event.

2. Metadata ❍ RowSetMetaData

This interface, derived from the ResultSetMetaData interface, provides information about the columns in a RowSet object. An application can use RowSetMetaData methods to find out how many columns the rowset contains and what kind of data each column can contain.

The RowSetMetaData interface provides methods for setting the information about columns, but an application would not normally use these methods. When an application calls the RowSet method execute, the RowSet object will contain a new set of rows,

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (5 of 7)8/18/2008 12:30:49 PM

Page 15: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

and its RowSetMetaData object will have been internally updated to contain information about the new columns.

3. The Reader/Writer Facility A RowSet object that implements the RowSetInternal interface can call on the RowSetReader object associated with it to populate itself with data. It can also call on the RowSetWriter object associated with it to write any changes to its rows back to the data source from which it originally got the rows. A rowset that remains connected to its data source does not need to use a reader and writer because it can simply operate on the data source directly.

❍ RowSetInternal By implementing the RowSetInternal interface, a RowSet object gets access to its internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current rows and of the values that immediately preceded the current ones, referred to as the original values. A rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection that was passed to it, if any. A rowset uses the RowSetInternal methods behind the scenes to get access to this information. An application does not normally invoke these methods directly.

❍ RowSetReader A disconnected RowSet object that has implemented the RowSetInternal interface can call on its reader (the RowSetReader object associated with it) to populate it with data. When an application calls the RowSet.execute method, that method calls on the rowset's reader to do much of the work. Implementations can vary widely, but generally a reader makes a connection to the data source, reads data from the data source and populates the rowset with it, and closes the connection. A reader may also update the RowSetMetaData object for its rowset. The rowset's internal state is also updated, either by the reader or directly by the method RowSet.execute.

❍ RowSetWriter A disconnected RowSet object that has implemented the RowSetInternal interface can call on its writer (the RowSetWriter object associated with it) to write changes back to the underlying data source. Implementations may vary widely, but generally, a writer will do the following:

■ Make a connection to the data source ■ Check to see whether there is a conflict, that is, whether a value that has been

changed in the rowset has also been changed in the data source ■ Write the new values to the data source if there is no conflict ■ Close the connection

The RowSet interface may be implemented in any number of ways, and anyone may write an implementation. Developers are encouraged to use their imaginations in coming up with new ways to use rowsets.

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (6 of 7)8/18/2008 12:30:49 PM

Page 16: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

javax.sql (Java Platform SE 6)

IMPORTANT NOTE: Code that uses API marked "Since 1.6" must be run using a JDBC technology driver that implements the JDBC 4.0 API. You must check your driver documentation to be sure that it implements the particular features you want to use.

Package Specification

● Specification of the JDBC 4.0 API

Related Documentation

The Java Series book published by Addison-Wesley Longman provides detailed information about the classes and interfaces in the javax.sql package:

● JDBCTM API Tutorial and Reference, Third Edition:

Since: 1.4

Overview Package Class Use Tree Deprecated Index Help Java™ Platform Standard Ed. 6

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES All Classes

Submit a bug or feature For further API reference and developer documentation, see Java SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.

Copyright 2006 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. Also see the

documentation redistribution policy.

http://java.sun.com/javase/6/docs/api/javax/sql/package-summary.html (7 of 7)8/18/2008 12:30:49 PM

Page 17: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

Apache Tomcat 6.0

Apache Tomcat 6.0

JNDI Resources HOW-TO

IntroductionTomcat 6 provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java2 Enterprise Edition application server. The J2EE standard provides a standard set of elements in the /WEB-INF/web.xml file to reference resources; resources referenced in these elements must be defined in an application-server-specific configuration.

For Tomcat 6, these entries in per-web-application InitialContext are configured in the <Context> elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file ( META-INF/context.xml).

Tomcat 6 maintains a separate namespace of global resources for the entire server. These are configured in the <GlobalNameingResources> element of $CATALINA_BASE/conf/server.xml. You may expose these resources to web applications by using <ResourceLink> elements.

The resources defined in these elements may be referenced by the following elements in the web application deployment descriptor (/WEB-INF/web.xml) of your web application:

● <env-entry> - Environment entry, a single-value parameter that can be used to configure how the application will operate.

● <resource-ref> - Resource reference, which is typically to an object factory for resources such as a JDBC DataSource, a JavaMail Session, or custom object factories configured into Tomcat 6.

● <resource-env-ref> - Resource environment reference, a new variation of resource-ref added in Servlet 2.4 that is simpler to configure for resources that do not require authentication information.

The InitialContext is configured as a web application is initially deployed, and is made available to web application components (for read-only access). All configured entries and resources are placed in the java:comp/env portion of the JNDI namespace, so a typical access to a resource - in this case, to a JDBC DataSource - would look something like this:

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (1 of 12)8/18/2008 2:33:29 PM

Page 18: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

// Obtain our environment naming contextContext initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data sourceDataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");

// Allocate and use a connection from the poolConnection conn = ds.getConnection();... use this connection to access the database ...conn.close();

See the following Specifications for more information about programming APIs for JNDI, and for the features supported by Java2 Enterprise Edition (J2EE) servers, which Tomcat emulates for the services that it provides:

● Java Naming and Directory Interface (included in JDK 1.4 onwards) ● J2EE Platform Specification (in particular, see Chapter 5 on Naming)

Configuring JNDI ResourcesEach available JNDI Resource is configured based on inclusion of the following elements in the <Context> element:

● <Environment> - Configure names and values for scalar environment entries that will be exposed to the web application through the JNDI InitialContext (equivalent to the inclusion of an <env-entry> element in the web application deployment descriptor).

● <Resource> - Configure the name and data type of a resource made available to the application (equivalent to the inclusion of a <resource-ref> element in the web application deployment descriptor).

● <ResourceLink> - Add a link to a resource defined in the global JNDI context. Use resource links to give a web application access to a resource defined in the<GlobalNamingResources> child element of the <Server> element.

● <Transaction> - Add a resource factory for instantiating the UserTransaction object instance that is available at java:comp/UserTransaction.

Any number of these elements may be nested inside a <Context> element (to be associated only with that particular web application).

In addition, the names and values of all <env-entry> elements included in the web application deployment descriptor (/WEB-INF/web.xml) are configured into the initial context as well, overriding corresponding values from the <Context> element only if allowed by the corresponding <Environment> element (by setting the override attribute to "true").

Global resources can be defined in the server-wide JNDI context, by adding the resource elements described above to the <GlobalNamingResources> child element of the <Server> element and using a <ResourceLink> to include it in the per-web-application context.

Tomcat Standard Resource Factories

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (2 of 12)8/18/2008 2:33:29 PM

Page 19: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

Tomcat 6 includes a series of standard resource factories that can provide services to your web applications, but give you configuration flexibility (via the <Context> element) without modifying the web application or the deployment descriptor. Each subsection below details the configuration and usage of the standard resource factories.

See Adding Custom Resource Factories for information about how to create, install, configure, and use your own custom resource factory classes with Tomcat 6.

NOTE - Of the standard resource factories, only the "JDBC Data Source" and "User Transaction" factories are mandated to be available on other platforms, and then they are required only if the platform implements the Java2 Enterprise Edition (J2EE) specs. All other standard resource factories, plus custom resource factories that you write yourself, are specific to Tomcat and cannot be assumed to be available on other containers.

Generic JavaBean Resources0. Introduction

This resource factory can be used to create objects of any Java class that conforms to standard JavaBeans naming conventions (i.e. it has a zero-arguments constructor, and has property setters that conform to the setFoo() naming pattern. The resource factory will create a new instance of the appropriate bean class every time a lookup() for this entry is made.

The steps required to use this facility are described below.

1. Create Your JavaBean Class

Create the JavaBean class which will be instantiated each time that the resource factory is looked up. For this example, assume you create a class com.mycompany.MyBean, which looks like this:

package com.mycompany;

public class MyBean {

private String foo = "Default Foo";

public String getFoo() { return (this.foo); }

public void setFoo(String foo) { this.foo = foo; }

private int bar = 0;

public int getBar() { return (this.bar); }

public void setBar(int bar) { this.bar = bar; }

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (3 of 12)8/18/2008 2:33:29 PM

Page 20: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

}

2. Declare Your Resource Requirements

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a <resource-env-ref> element, like this:

<resource-env-ref> <description> Object factory for MyBean instances. </description> <resource-env-ref-name> bean/MyBeanFactory </resource-env-ref-name> <resource-env-ref-type> com.mycompany.MyBean </resource-env-ref-type></resource-env-ref>

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

3. Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " + bean.getBar());

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an element like this to the <Context> element for this web application.

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (4 of 12)8/18/2008 2:33:29 PM

Page 21: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

<Context ...> ... <Resource name="bean/MyBeanFactory" auth="Container" type="com.mycompany.MyBean" factory="org.apache.naming.factory.BeanFactory" bar="23"/> ...</Context>

Note that the resource name (here, bean/MyBeanFactory must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.

JavaMail Sessions0. Introduction

In many web applications, sending electronic mail messages is a required part of the system's functionality. The Java Mail API makes this process relatively straightforward, but requires many configuration details that the client application must be aware of (including the name of the SMTP host to be used for message sending).

Tomcat 6 includes a standard resource factory that will create javax.mail.Session session instances for you, already configured to connect to an SMTP server. In this way, the application is totally insulated from changes in the email server configuration environment - it simply asks for, and receives, a preconfigured session whenever needed.

The steps required for this are outlined below.

1. Declare Your Resource Requirements

The first thing you should do is modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured sessions. By convention, all such names should resolve to the mail subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

<resource-ref> <description> Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured to connect to the appropriate SMTP server. </description> <res-ref-name> mail/Session </res-ref-name> <res-type> javax.mail.Session

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (5 of 12)8/18/2008 2:33:29 PM

Page 22: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

</res-type> <res-auth> Container </res-auth></resource-ref>

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

2. Code Your Application's Use Of This Resource

A typical use of this resource reference might look like this:

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);message.setFrom(new InternetAddress(request.getParameter("from"));InternetAddress to[] = new InternetAddress[1];to[0] = new InternetAddress(request.getParameter("to"));message.setRecipients(Message.RecipientType.TO, to);message.setSubject(request.getParameter("subject"));message.setContent(request.getParameter("content"), "text/plain");Transport.send(message);

Note that the application uses the same resource reference name that was declared in the web application deployment descriptor. This is matched up against the resource factory that is configured in the <Context> element for the web application as described below.

3. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the <Context> element for this web application.

<Context ...> ... <Resource name="mail/Session" auth="Container" type="javax.mail.Session" mail.smtp.host="localhost"/> ...</Context>

Note that the resource name (here, mail/Session) must match the value specified in the web application deployment descriptor. Customize the value of the mail.smtp.host parameter to point at the server that provides SMTP service for your network.

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (6 of 12)8/18/2008 2:33:29 PM

Page 23: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

4. Install the JavaMail libraries

Download the JavaMail API. The JavaMail API requires the Java Activation Framework (JAF) API as well. The Java Activation Framework can be downloaded from Sun's site.

This download includes 2 vital libraries for the configuration; activation.jar and mail.jar. Unpackage both distributions and place them into $CATALINA_HOME/lib so that they are available to Tomcat during the initialization of the mail Session Resource. Note: placing these jars in both $CATALINA_HOME/lib and a web application's lib folder will cause an error, so ensure you have them in the $CATALINA_HOME/lib location only.

Example Application

The /examples application included with Tomcat contains an example of utilizing this resource factory. It is accessed via the "JSP Examples" link. The source code for the servlet that actually sends the mail message is in /WEB-INF/classes/SendMailServlet.java.

WARNING - The default configuration assumes that there is an SMTP server listing on port 25 on localhost. If this is not the case, edit the <Context> element for this web application and modify the parameter value for the mail.smtp.host parameter to be the host name of an SMTP server on your network.

JDBC Data Sources0. Introduction

Many web applications need to access a database via a JDBC driver, to support the functionality required by that application. The J2EE Platform Specification requires J2EE Application Servers to make available a DataSource implementation (that is, a connection pool for JDBC connections) for this purpose. Tomcat 6 offers exactly the same support, so that database-based applications you develop on Tomcat using this service will run unchanged on any J2EE server.

For information about JDBC, you should consult the following:

● http://java.sun.com/products/jdbc/ - Home page for information about Java Database Connectivity.

● http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html - The JDBC 2.1 API Specification.

● http://java.sun.com/products/jdbc/jdbc20.stdext.pdf - The JDBC 2.0 Standard Extension API (including the javax.sql.DataSource API). This package is now known as the "JDBC Optional Package".

● http://java.sun.com/j2ee/download.html - The J2EE Platform Specification (covers the JDBC facilities that all J2EE platforms must provide to applications).

NOTE - The default data source support in Tomcat is based on the DBCP connection pool from the Commons project. However, it is possible to use any other connection pool that implements javax.sql.DataSource, by writing your own custom resource factory, as described below.

1. Install Your JDBC Driver

Use of the JDBC Data Sources JNDI Resource Factory requires that you make an appropriate JDBC driver available to both Tomcat internal classes and to your web application. This is most easily

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (7 of 12)8/18/2008 2:33:29 PM

Page 24: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

accomplished by installing the driver's JAR file(s) into the $CATALINA_HOME/lib directory, which makes the driver available both to the resource factory and to your application.

2. Declare Your Resource Requirements

Next, modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured data source. By convention, all such names should resolve to the jdbc subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

<resource-ref> <description> Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the <Context> configurartion for the web application. </description> <res-ref-name> jdbc/EmployeeDB </res-ref-name> <res-type> javax.sql.DataSource </res-type> <res-auth> Container </res-auth></resource-ref>

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

3. Code Your Application's Use Of This Resource

A typical use of this resource reference might look like this:

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();... use this connection to access the database ...conn.close();

Note that the application uses the same resource reference name that was declared in the web application deployment descriptor. This is matched up against the resource factory that is configured in the <Context> element for the web application as described below.

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (8 of 12)8/18/2008 2:33:29 PM

Page 25: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an element like this to the <Context> element for the web application.

<Context ...> ... <Resource name="jdbc/EmployeeDB" auth="Container" type="javax.sql.DataSource" username="dbusername" password="dbpassword" driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database" maxActive="8" maxIdle="4"/> ...</Context>

Note that the resource name (here, jdbc/EmployeeDB) must match the value specified in the web application deployment descriptor.

This example assumes that you are using the HypersonicSQL database JDBC driver. Customize the driverClassName and driverName parameters to match your actual database's JDBC driver and connection URL.

The configuration properties for Tomcat's standard data source resource factory (org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory) are as follows:

● driverClassName - Fully qualified Java class name of the JDBC driver to be used. ● maxActive - The maximum number of active instances that can be allocated from this pool at

the same time. ● maxIdle - The maximum number of connections that can sit idle in this pool at the same time. ● maxWait - The maximum number of milliseconds that the pool will wait (when there are no

available connections) for a connection to be returned before throwing an exception. ● password - Database password to be passed to our JDBC driver. ● url - Connection URL to be passed to our JDBC driver. (For backwards compatibility, the

property driverName is also recognized.) ● user - Database username to be passed to our JDBC driver. ● validationQuery - SQL query that can be used by the pool to validate connections before

they are returned to the application. If specified, this query MUST be an SQL SELECT statement that returns at least one row.

For more details, please refer to the commons-dbcp documentation.

Adding Custom Resource Factories

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (9 of 12)8/18/2008 2:33:29 PM

Page 26: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

If none of the standard resource factories meet your needs, you can write your own factory and integrate it into Tomcat 6, and then configure the use of this factory in the <Context> element for the web application. In the example below, we will create a factory that only knows how to create com.mycompany.MyBean beans from the Generic JavaBean Resources example above.

1. Write A Resource Factory Class

You must write a class that implements the JNDI service provider javax.naming.spi.ObjectFactory inteface. Every time your web application calls lookup() on a context entry that is bound to this factory, the getObjectInstance() method is called, with the following arguments:

● Object obj - The (possibly null) object containing location or reference information that can be used in creating an object. For Tomcat, this will always be an object of type javax.naming.Reference, which contains the class name of this factory class, as well as the configuration properties (from the <Context> for the web application) to use in creating objects to be returned.

● Name name - The name to which this factory is bound relative to nameCtx, or null if no name is specified.

● Context nameCtx - The context relative to which the name parameter is specified, or null if name is relative to the default initial context.

● Hashtable environment - The (possibly null) environment that is used in creating this object. This is generally ignored in Tomcat object factories.

To create a resource factory that knows how to produce MyBean instances, you might create a class like this:

package com.mycompany;

import java.util.Enumeration;import java.util.Hashtable;import javax.naming.Context;import javax.naming.Name;import javax.naming.NamingException;import javax.naming.RefAddr;import javax.naming.Reference;import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws NamingException {

// Acquire an instance of our specified bean class MyBean bean = new MyBean();

// Customize the bean properties from our attributes Reference ref = (Reference) obj; Enumeration addrs = ref.getAll(); while (addrs.hasMoreElements()) { RefAddr addr = (RefAddr) addrs.nextElement(); String name = addr.getType(); String value = (String) addr.getContent(); if (name.equals("foo")) { bean.setFoo(value);

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (10 of 12)8/18/2008 2:33:29 PM

Page 27: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

} else if (name.equals("bar")) { try { bean.setBar(Integer.parseInt(value)); } catch (NumberFormatException e) { throw new NamingException("Invalid 'bar' value " + value); } } }

// Return the customized instance return (bean);

}

}

In this example, we are unconditionally creating a new instance of the com.mycompany.MyBean class, and populating its properties based on the parameters included in the <ResourceParams> element that configures this factory (see below). You should note that any parameter named factory should be skipped - that parameter is used to specify the name of the factory class itself (in this case, com.mycompany.MyBeanFactory) rather than a property of the bean being configured.

For more information about ObjectFactory, see the JNDI 1.2 Service Provider Interface (SPI) Specification.

You will need to compile this class against a class path that includes all of the JAR files in the $CATALINA_HOME/lib directory. When you are through, place the factory class (and the corresponding bean class) unpacked under $CATALINA_HOME/lib, or in a JAR file inside $CATALINA_HOME/lib. In this way, the required class files are visible to both Catalina internal resources and your web application.

2. Declare Your Resource Requirements

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a <resource-env-ref> element, like this:

<resource-env-ref> <description> Object factory for MyBean instances. </description> <resource-env-ref-name> bean/MyBeanFactory </resource-env-ref-name> <resource-env-ref-type> com.mycompany.MyBean </resource-env-ref-type><resource-env-ref>

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (11 of 12)8/18/2008 2:33:29 PM

Page 28: Package java.sql Interface Summarynduan/swe642/spring10/Session6-JDBC/JDBCand... · java.sql (Java Platform SE 6) SQLNonTransientConnectionException The subclass of SQLException thrown

Apache Tomcat 6.0 - JNDI Resources HOW-TO

3. Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " + bean.getBar());

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the <Context> element for this web application.

<Context ...> ... <Resource name="bean/MyBeanFactory" auth="Container" type="com.mycompany.MyBean" factory="com.mycompany.MyBeanFactory" bar="23"/> ...</Context>

Note that the resource name (here, bean/MyBeanFactory must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.

You will also note that, from the application developer's perspective, the declaration of the resource environment reference, and the programming used to request new instances, is identical to the approach used for the Generic JavaBean Resources example. This illustrates one of the advantages of using JNDI resources to encapsulate functionality - you can change the underlying implementation without necessarily having to modify applications using the resources, as long as you maintain compatible APIs.

Copyright © 1999-2008, Apache Software Foundation

http://tomcat.apache.org/tomcat-6.0-doc/printer/jndi-resources-howto.html (12 of 12)8/18/2008 2:33:29 PM