blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

Why DataSource

Why DataSource and not DriverManager?

Answer is simple. That's how the API evolved.
Java 1.7 docs states that "The DataSource interface, new in the JDBC 2.0 API, provides another way to connect to a data source. An alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection."

Using DataSource instead of DriverManager

DriverManager has one significant drawback: It requires hard-coding vendor options and details about the database and server configurations. To use the code on another system, to change the database, or to change username or password, etc., we may need to edit the source code, recompile, and retest.

There are several approaches that we can take to minimize this problem. One option is to put these specifics in a properties file or a configuration file that is read at startup time, perhaps using XML or a Java ResourceBundle . These minimize but don't solve the problem.

In JDBC 2.0, Sun introduced an alternative with a more far-reaching approach, the DataSource class.
  • DataSource allows our code to locate and connect to a resource, such as a database, by using a logical name . This can make our code more portable and easier to maintain.
  • It also allows us to encapsulate some of the connection details at a higher-level— a naming service such as Java Naming and Directory Interface (JDNI).
  • Most of the implementations of DataSource inherently supports connection pooling.
Unlike DriverManager class that came with JDK itself, DataSource is not a class but a interface.

We could choose a DataSource implementation from 3 choices:

  1. Choose that comes with the jdbc driver.
  2. Choose a external /library like commons-dbcp.
  3. Choose container provided implementation.

Note that the 3 examples that follow do not take advantage of the primary benefits of DataSource - JNDI.
We will look at JDNI later.
Also DataSource has the same limitations as DriverManager when it comes to connection handling. Meaning, connection sharing is dangerous and connections are not pooled/nor closed (unless proper configurations or handlers are written).

Continue reading: JDBC connections using DataSouce (driver implementation)

No comments:

Post a Comment