100% found this document useful (1 vote)
4K views50 pages

Javax SQL Package

The document discusses the javax.sql package which provides APIs for server-side data source access and processing. It supplements the java.sql package and provides interfaces like DataSource for connection pooling, distributed transactions, and rowsets. The document discusses how applications use DataSource objects retrieved from JNDI to get pooled database connections that support features like connection pooling and distributed transactions transparently.

Uploaded by

Sudhanshu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4K views50 pages

Javax SQL Package

The document discusses the javax.sql package which provides APIs for server-side data source access and processing. It supplements the java.sql package and provides interfaces like DataSource for connection pooling, distributed transactions, and rowsets. The document discusses how applications use DataSource objects retrieved from JNDI to get pooled database connections that support features like connection pooling and distributed transactions transparently.

Uploaded by

Sudhanshu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd

[Link].

* Package
• Provides the API for server side data
source access and processing.
• This package supplements the [Link].*
package and, as of the version 1.4
release, is included in the Java Platform,
Standard Edition.
• It remains an essential part of the Java
Platform, Enterprise Edition.
• The [Link] package provides for the
following:
• The DataSource interface as an
alternative to the DriverManager for
establishing a connection with a data
source.
• Connection pooling
• Distributed transactions
• 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.
DataSource Object

• 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 Interface
(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.
Java Naming and Directory
Interface (JNDI)
• Naming and directory services play a vital role in
intranets and the Internet by providing network-
wide sharing of a variety of information about
users, machines, networks, services, and
applications.
• JNDI is an API specified in Java technology that
provides naming and directory functionality to
applications written in the Java programming
language.
Java Naming and Directory Interface (JNDI)

• Using JNDI, applications based on Java


technology can store and retrieve named Java
objects of any type.
• In addition, JNDI provides methods for
performing standard directory operations, such
as associating attributes with objects and
searching for objects using their attributes.
Java Naming and Directory
Interface (JNDI)
• It enables applications to access different,
possibly multiple, naming and directory services
using a common API.

• Different naming and directory service providers


can be plugged in seamlessly behind this
common API.
Creating and Registering a
DataSource Object
VendorDataSource vds = new
VendorDataSource();
[Link]("my_database_server");
[Link]("my_database");
[Link]("the data source for
inventory and personnel");
Context ctx = new InitialContext();
[Link]("jdbc/AcmeDB", vds);
• The first four lines represent API from a
vendor's class VendorDataSource, an
implementation of the
[Link] interface.
• They create a DataSource object, vds, and
set its serverName, databaseName, and
description properties.
• The fifth and sixth lines use JNDI API to
register vds with a JNDI naming service.
• The fifth line calls the default InitialContext
constructor to create a Java object that
references the initial JNDI naming context.
• System properties, which are not shown
here, tell JNDI which naming service
provider to use.
• The last line associates vds with a logical
name for the data source that vds
represents.
Connecting to a Data Source
Context ctx = new InitialContext();
DataSource ds =
(DataSource)[Link]("jdbc/AcmeDB");
Connection con =
[Link]("genius",
"abracadabra");
Advantages of Using JNDI
• There are major advantages to connecting to
a data source using a DataSource object
registered with a JNDI naming service rather
than using the DriverManager facility.
• The first is that it makes code more portable.
• With the DriverManager, the name of a
JDBC driver class, which usually identifies a
particular driver vendor, is included in
application code. This makes the application
specific to that vendor's driver product and
thus non-portable.
• Another advantage is that it makes code
much easier to maintain. If any of the
necessary information about the data
source changes, only the relevant
DataSource properties need to be
modified, not every application that
connects to that data source.
• For example, if a database is moved to a
different server and uses a different port
number, only the DataSource object's
serverName and portNumber properties
need to be updated.
• Yet another advantage is that applications
using a DataSource object to get a
connection will automatically benefit from
connection pooling if the DataSource class
has been implemented to support
connection pooling.
• Likewise, an application will automatically
be able to use distributed transactions if
the DataSource class has been
implemented to support them.
• What is LDAP?
• LDAP, Lightweight Directory Access
Protocol, is an Internet protocol that
email and other programs use to look
up information from a server
Connection Pooling
• Originally, JDBC 1.0 defined the Java APIs for
access to relational databases.
• With the introduction of JDBC 2.0, the APIs
were split into two parts:
• The JDBC 2.0 Core API
• This contains evolutionary improvements but
has been kept small and focused like the JDBC
1.0 API in order to promote ease of use. Code
written for the 1.0 API continues to work with the
2.0 API. The 2.0 API classes remain in the
[Link] package.
• The JDBC 2.0 Optional Package API
• This supports integration with additional
Java standards, including JNDI (Java
Naming and Directory Interface), JTA (Java
Transaction API), and EJB (Enterprise
JavaBeans), as well as providing support
for connection pooling and Java beans.
• Connection pooling is the maintenance of a
group of database connections for reuse by
applications on an application server.
• Connection pooling allows the idle
connection to be used by some other thread
to do useful work.
• In practice, a thread requests a connection
from the pool.
• When the thread is finished using the
connection, it returns it to the pool, so that it
may be used by any other threads that want
to use it.
Benefits of Connection
Pooling
• Reduced connection creation time:
JDBC driver overhead can be avoided if
connections are "recycled.“
• Simplified programming model:
Allowing you to use straight-forward JDBC
programming techniques.
• Controlled resource usage :
Connection pools can be tuned to
maximize performance, while keeping
resource utilization below.
Connection Pooling
Implementation
• Generally, you configure a connection pool
in your application server configuration
files, and access it via the Java Naming
and Directory Interface (JNDI).
• Connection pooling is totally transparent. It
is done automatically in the middle tier of a
J2EE configuration, so from an
application's viewpoint, no change in code
is required.
• An application simply uses the
[Link] method to get
the pooled connection and uses it the
same way it uses any Connection object.
• The classes and interfaces used for
connection pooling are:
• ConnectionPoolDataSource
• PooledConnection
• ConnectionEvent
• ConnectionEventListener
• The connection pool manager, a facility in
the middle tier of a three-tier architecture,
uses these classes and interfaces behind
the scenes.
• Application code to initialize a pooling
DataSource and add it to JNDI might look
like this:
Jdbc3PoolingDataSource source = new
Jdbc3PoolingDataSource();
[Link]("A Data Source");
[Link]("localhost");
[Link]("test");
[Link]("testuser");
[Link]("testpassword");
[Link](10);
new InitialContext().rebind("DataSource",
source);
• Then code to use a connection from the
pool might look like this:
Connection con = null;
try { DataSource source = (DataSource) new
InitialContext().lookup("DataSource");
con = [Link]();
// use connection
}
catch(SQLException e) { // log error }
catch(NamingException e) { // DataSource wasn't
found in JNDI }
finally { if(con != null) { try {[Link]();}
catch(SQLException e) {} } }
• Note that it is critical that the connections
are closed, or else the pool will "leak"
connections, and eventually lock all the
clients out.
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.
Distributed Transactions
• A transaction manager in the middle tier
handles everything transparently.
• An application cannot call the methods
[Link] or
[Link], and it cannot set the
connection to be in auto-commit mode
(that is, it cannot call
[Link](true)).
Distributed Transactions
• 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
[Link] method, just
as it normally does.
Distributed Transactions
• 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
• A RowSet object contains a set of rows from
a result set or some other source of tabular
data, like a file or spreadsheet.
• Because a RowSet object follows the
JavaBeans model for properties and event
notification, it is a JavaBeans component
that can be combined with other components
in an application.
• Rowsets make it easy to send tabular data
over a network.
RowSets (Contd..)
• Two broad categories, rowsets that are
connected and those that are
disconneced.
• A disconnected rowset gets a connection
to a data source in order to fill itself with
data or to propagate changes in data back
to the data source, but most of the time it
does not have a connection open.
• A disconnected rowset stores its data in
memory.
RowSets (Contd..)
• A connected rowset, by contrast, opens a
connection and keeps it open for as long
as the rowset is in use.
Types of RowSets
• A CachedRowSet class—a disconnected
rowset that caches its data in memory; not
suitable for very large data sets, but an
ideal way to provide thin Java clients, such
as a Personal Digital Assistant (PDA) or
Network Computer (NC), with tabular data.
• A JDBCRowSet class—a connected rowset
that serves mainly as a thin wrapper around
a ResultSet object to make a JDBC driver
look like a JavaBeans component.
Types of RowSets (Contd..)
• A WebRowSet class—a connected rowset
that uses the HTTP protocol internally to
talk to a Java servlet that provides data
access; used to make it possible for thin
web clients to retrieve and possibly update
a set of rows.
CachedRowSet Example
• The code for creating a CachedRowSet object
simply uses the default constructor.

CachedRowSet crset = new CachedRowSet();


[Link]("SELECT * FROM COFFEES");
[Link]("jdbc/coffeesDB");
[Link]("juanvaldez");
[Link]("espresso");
[Link]();
while ([Link]())
{ [Link]([Link]("COF_NAME"));
}
JdbcRowSet Example
JdbcRowSet jdbcRs2 = new JdbcRowSetImpl();
[Link]("hardy");
[Link]("oursecret");
[Link]("jdbc:mySubprotocol:mySubname");
[Link]("select * from COFFEES");
[Link]();
JdbcRowSet Example (Contd..)
while ([Link]()) {
String name =
[Link]("COF_NAME");
String price = [Link]("PRICE");
[Link](name);
[Link](price);
}
WebRowSet
• A WebRowSet object is very special because in addition
to offering all of the capabilities of a CachedRowSet
object, it can write itself as an XML document and can
also read that XML document to convert itself back to a
WebRowSet object.
• Because XML is the language through which disparate
enterprises can communicate with each other, it has
become the standard for Web Services communication.
• As a consequence, a WebRowSet object fills a real need
by making it easy for Web Services to send and receive
data from a database in the form of an XML document.
WebRowSet Example
WebRowSet priceList = new
WebRowSetImpl();
[Link]("SELECT
COF_NAME, PRICE FROM COFFEES");
[Link]("jdbc:mySubprotocol:myDa
tabase");
[Link]("myUsername");
[Link]("myPassword");
[Link]();
Writing and Reading a WebRowSet
Object to XML
• The method writeXML writes the
WebRowSet object that invoked it as an
XML document.
• It writes this XML document to the stream
that pass to it.
Writing and Reading a WebRowSet
Object to XML (Contd..)
• The stream can be an OutputStream
object, such as a FileOutputStream object,
or a Writer object, such as a FileWriter
object.
• If you pass the method writeXml an
OutputStream object, you will write in bytes,
which can handle all types of data; if you pass it
a Writer object, you will write in characters.
Writing and Reading a WebRowSet
Object to XML (Contd..)
• The following code demonstrates writing
the WebRowSet object priceList as an
XML document to the FileOutputStream
object oStream.
[Link] oStream = new
[Link]("[Link]");
[Link](oStream);
Writing and Reading a WebRowSet
Object to XML (Contd..)
• The following code writes the XML
document representing priceList to the
FileWriter object writer.

[Link] writer = new


[Link]("[Link]");
[Link](writer);
Writing and Reading a WebRowSet
Object to XML (Contd..)
• The method readXml parses an XML
document in order to construct the
WebRowSet object the XML document
describes. Analogous to the method
writeXml, you can pass readXml an
InputStream object or a Reader object
from which to read the XML document.
Writing and Reading a WebRowSet
Object to XML (Contd..)
InputStream object example :-
[Link] iStream = new
[Link]("[Link]");
[Link](iStream);
Reader object Example :-
[Link] reader = new
[Link]("[Link]");
[Link](reader);

Common questions

Powered by AI

Using a DataSource object over DriverManager offers several advantages. Firstly, it allows changes to be made to a data source's properties without altering application code when something about the data source or driver changes . Secondly, DataSource supports connection and statement pooling and distributed transactions, which are not available with DriverManager. This results in better performance and resource management as it allows reuse of connections and integration with middle-tier infrastructure, enhancing scalability and reliability of applications . Thirdly, applications using DataSource registered with JNDI become more portable and maintainable, as they are not tied to a specific driver vendor's product . Finally, applications benefit from connection pooling automatically if the DataSource implementation supports it, which can significantly reduce connection creation time and resource usage .

Connection pooling and distributed transactions complement each other to improve enterprise application performance by addressing different levels of resource optimization and transactional integrity. Connection pooling optimizes the database connectivity aspect by reusing a finite number of connections within a pool, significantly reducing the overhead associated with repeatedly opening and closing connections. This not only enhances application responsiveness but also allows more predictable and manageable database resource utilization . On the other hand, distributed transactions ensure that multi-database operations can proceed with ACID properties across multiple databases or resource managers. When integrated, connection pooling provides a robust infrastructure that supports the transactional capabilities of distributed transaction management by ensuring that the necessary connections are efficiently managed and available when needed, thus enhancing the overall scalability and robustness of enterprise applications .

JNDI enhances the portability and maintainability of Java applications by providing a decoupled approach to resource lookup. Instead of hardcoding the connection details or specific driver classes in the application code, JNDI allows the registration and lookup of DataSource objects using logical names. This abstraction makes the application code independent of specific resource details, enabling seamless changes to these details without any modifications to the application code. When a database is moved or renamed, only the properties of the DataSource in JNDI need updating, not the application itself . This separation facilitates easier code maintenance and portability across different environments and server configurations .

In a Java enterprise environment, distributed transactions are managed transparently by a transaction manager in the middle tier. The transaction manager uses interfaces such as XADataSource and XAConnection to manage connections that span multiple resource managers. These interfaces create XAResource objects which the transaction manager uses to coordinate transactions across multiple database servers. Application developers interact with data sources just as they would in a non-distributed environment; the complexity of managing transactions across multiple resources is handled by the transaction manager . This enables a single transaction to include operations across multiple databases or systems while maintaining atomicity, consistency, isolation, and durability (ACID properties).

Connected RowSets maintain an open connection to their data source while being used, which allows them to be constantly updated with live data and supports immediate data updates back to the data source. A common use case for connected RowSets is when an application needs real-time data access and updates, such as in dynamic reporting or monitoring applications . Disconnected RowSets, such as CachedRowSets, establish connections only temporarily to perform operations like data loading or updates, but primarily keep their data in memory. This makes them suitable for scenarios where data needs to be manipulated offline, like in mobile or remote applications where continuous connectivity isn't guaranteed .

JNDI plays a crucial role in Java EE environments by serving as a uniform interface for accessing various naming and directory services. For connection pooling, JNDI allows pool configurations to be defined in application server settings, abstracting the pool specifics from the application code. This ensures that applications benefit from efficient connection reuse and management without requiring code changes, thus optimizing resource usage and performance . In distributed transactions, JNDI provides a mechanism for applications to access and utilize transaction resources uniformly across different systems, facilitating seamless integration with multiple transactional resources. This consistent and flexible resource management simplifies the architecture of distributed applications and contributes to their robustness and scalability .

Not properly closing connections in a connection pool can lead to resource leaks, where connections remain open and unavailable to other threads, potentially exhausting the pool and causing application failures or performance degradation. This is referred to as 'connection leak,' and can eventually lead to clients being locked out from accessing the database . These risks can be mitigated by ensuring that connections are always closed in a finally block in application code to guarantee that they are returned to the pool regardless of any exceptions that occur. Additionally, implementing monitoring and connection validation mechanisms can help in identifying and correcting connection leaks promptly .

The JavaBean properties of RowSet objects offer significant benefits to Java enterprise applications by providing a standard way to define and manipulate data components with properties, events, and persistence capabilities. As JavaBeans, RowSet objects can be easily integrated with other components, facilitating component-based application development. This model supports property change notifications and event handling, allowing applications to respond dynamically to data changes. Furthermore, RowSet properties can be manipulated using tools that support JavaBeans, enhancing visual development and reducing manual coding. The ability to serialize RowSets supports their use in distributed systems by allowing them to be transmitted over a network or saved between application sessions, thus improving flexibility and ease of integration in enterprise systems .

A WebRowSet object facilitates data exchange by allowing its contents to be written to and read from XML documents. This capability provides several benefits: it enables interoperability between different systems, as XML is a platform-independent format widely used in web services; it allows easy integration with XML-based tools and technologies; and it provides a flexible means of serializing data for transmission over the web or storage. By writing a RowSet as XML, enterprises can easily exchange data between different components or systems that adhere to XML standards, making WebRowSet an effective tool for building distributed applications or web services .

Connection pooling enhances database connection efficiency by reducing the overhead associated with creating and destroying database connections, which are resource-intensive operations. The pool maintains a set of reusable connections. Threads needing database access borrow connections from the pool, perform their operations, and return them to the pool, rather than opening new connections each time. This reduces the time needed to establish connections and allows better management of database resources . Furthermore, pooling minimizes the latency in application response times and maximizes throughput, thereby improving the performance and scalability of the application .

You might also like