The vehicle insert operation is a typical JDBC update scenario. Each time this method is called, you
obtain a connection from the data source and execute the SQL statement on this connection. Your DAO
interface doesn't declare throwing any checked exceptions, so if a SQLException occurs, you have to wrap
it with an unchecked RuntimeException . (There is a detailed discussion on handling Exceptions in your
DAOs later in this chapter). Finally, don't forget to release the connection in the finally block. Failing to
do so may cause your application to run out of connections.
Here, the update and delete operations will be skipped because they are much the same as the
insert operation from a technical point of view. For the query operation, you have to extract the data
from the returned result set to build a vehicle object in addition to executing the SQL statement.
Configuring a Data Source in Spring
The javax.sql.DataSource interface is a standard interface defined by the JDBC specification that
factories Connection instances. There are many data source implementations provided by different
vendors and projects: C3PO and Apache Commons DBCP are popular open source options, and most
applications servers will provide their own implementation. It is very easy to switch between different
data source implementations because they implement the common DataSource interface. As a Java
application framework, Spring also provides several convenient but less powerful data source
implementations. The simplest one is DriverManagerDataSource , which opens a new connection every
time it's requested.
Note To access a database instance running on the Derby server, you have to include derbyclient.jar
(located in the lib directory of the Derby installation) in your classpath.
<beans xmlns=" http://www.springframework.org/schema/beans"
value="jdbc: derby://localhost:1527/vehicle;c reate=true" />
<property name="username" value="app" />
<property name="password" value="app" />
<property name="dataSource" ref="dataSource" />
DriverManagerDataSource is not an efficient data source implementation because it opens a new
connection for the client every time it's requested. Another data source implementation provided by
Spring is SingleConnectionDataSource (a DriverManagerDataSource subclass) . As its name indicates,