Exploring the JDBC Infrastructure

JDBC provides a standard way for Java applications to access data stored in a database. The core of the JDBC infrastructure is a driver that is specific to each database; it is this driver that allows Java code to access the database.

Once a driver is loaded, it registers itself with a java.sql.DriverManager class. This class manages a list of drivers and provides static methods for establishing connections to the database. The DriverManager's getConnection() method returns a driver-implemented java.sql.Connection interface. This interface allows you to run SQL statements against the database.

The JDBC framework is quite complex and well tested; however, with this complexity comes difficulty in development. The first level of complexity lies in making sure your code manages the connections to the database. A connection is a scarce resource and is very expensive to establish. Generally, the database creates a thread or spawns a child process for each connection. Also, the number of concurrent connections is usually limited, and an excessive number of open connections slows the database down.

We will show you how Spring helps manage this complexity, but before we can proceed any further, we need to show you how to select, delete, and update data in pure JDBC.

In Listing 8-1, we create a simple DAO interface with methods for selecting all entries, creating a new entry, and deleting an entry from the database. Keeping in mind what we already know about database connections, we take the cautious and expensive approach of creating a connection for each statement. This greatly degrades the performance of Java and adds extra stress to the database because a connection has to be established for each query. However, if we kept a connection open, we could bring the database server to a halt. In Listing 8-1, the TestDao interface is empty for the moment; we will add appropriate methods to it later.

Listing 8-1: Creating a JDBC Connection

image from book
public class PlainTestDao implements TestDao {          static {         try {             Class.forName("org.gjt.mm.mysql.Driver");         } catch (ClassNotFoundException ex) {             // noop         }     }          private Connection getConnection() throws SQLException {         return DriverManager.             getConnection("jdbc:mysql://localhost:3306/psch10", "janm", "");     }          private void closeConnection(Connection connection) {         if (connection == null) return;                  try {             connection.close();         } catch (SQLException ex) {             // noop         }     } }
image from book

This code is far from complete, but it gives you an idea of the steps you need to perform to just open a connection. This code does not even deal with connection pooling, a common technique for managing connections to the database more effectively. We do not discuss connection pooling at this point (connection pooling is discussed in the "Database Connections and DataSources" section later in this chapter); instead, in Listing 8-2, we show a full implementation of our DAO class using plain JDBC.

Listing 8-2: Plain JDBC DAO Implementation

image from book
package com.apress.prospring.ch10.plain;      // imports omitted for clarity public class PlainTestDao implements TestDao {          static {         try {             Class.forName("org.gjt.mm.mysql.Driver");         } catch (ClassNotFoundException ex) {             // noop         }     }          private Connection getConnection() throws SQLException {         return DriverManager.getConnection("jdbc:mysql://localhost:3306/psch10",             "janm", "");     }          private void closeConnection(Connection connection) {         if (connection == null) return;                  try {             connection.close();         } catch (SQLException ex) {             // noop         }     }          public List getAll() {         List result = new ArrayList();                  Connection connection = null;         try {             connection = getConnection();             PreparedStatement statement = connection.prepareStatement(                 "select * from Test");             ResultSet resultSet = statement.executeQuery();             while (resultSet.next()) {                 Test test = new Test();                 test.setName(resultSet.getString("Name"));                 test.setTestId(resultSet.getInt("TestId"));                 result.add(test);             }         } catch (SQLException ex) {             ex.printStackTrace();         } finally {             closeConnection(connection);         }                  return result;     }          public void insert(Test test) {         Connection connection = null;         try {             connection = getConnection();             PreparedStatement statement = connection.prepareStatement(                 "insert into Test (Name) values (?)");             statement.setString(1, test.getName());             statement.execute();                          ResultSet generatedKeys = statement.getGeneratedKeys();              if (generatedKeys.next()) {                 test.setTestId(generatedKeys.getInt("TestId"));             }         } catch (SQLException ex) {             ex.printStackTrace();         } finally {             closeConnection(connection);         }     }          public void delete(int testId) {         Connection connection = null;         try {             connection = getConnection();             PreparedStatement statement = connection.prepareStatement(                  "delete from Test where TestId=?");             statement.setInt(1, testId);             statement.execute();         } catch (SQLException ex) {             ex.printStackTrace();         } finally {             closeConnection(connection);         }     } }
image from book

As you can see from this listing, a lot of code needs to be moved to a helper class or—even worse—duplicated in each DAO class. This is the main disadvantage of JDBC from the application programmer's point of view—you just do not have time to code dull and repeated code in every DAO class. Instead, you want to concentrate on writing code that actually does what you need the DAO class to do: select, update, and delete the data. The more helper code you need to write, the more checked exceptions you need to handle, and the more bugs you may introduce in your code.

This is where a DAO framework and Spring come in. The framework eliminates the code that does not actually perform any custom logic and allows you to forget about all the housekeeping that needs to be performed and Spring's extensive JDBC support makes your life a lot easier.



Pro Spring
Pro Spring
ISBN: 1590594614
EAN: 2147483647
Year: 2006
Pages: 189

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net