Java Reference
In-Depth Information
For your vehicle registration application, you can abstract the data access operations to insert,
update, delete, and query a vehicle. These operations should be declared in a DAO interface to allow for
different DAO implementation technologies.
package com.apress.springenterpriserecipes.vehicle;
public interface VehicleDao {
public void insert(Vehicle vehicle);
public void update(Vehicle vehicle);
public void delete(Vehicle vehicle);
public Vehicle findByVehicleNo(String vehicleNo);
Most parts of the JDBC APIs declare throwing java.sql.SQLException . But because this interface
aims to abstract the data access operations only, it should not depend on the implementation
technology. So, it's unwise for this general interface to declare throwing the JDBC-specific SQLException .
A common practice when implementing a DAO interface is to wrap this kind of exception with a runtime
exception (either your own business Exception subclass or a generic one).
Implementing the DAO with JDBC
To access the database with JDBC, you create an implementation for this DAO interface (e.g.,
JdbcVehicleDao ). Because your DAO implementation has to connect to the database to execute SQL
statements, you may establish database connections by specifying the driver class name, database URL,
username, and password. However, in JDBC 2.0 or higher, you can obtain database connections from a
preconfigured javax.sql.DataSource object without knowing about the connection details.
package com.apress.springenterpriserecipes.vehicle;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class JdbcVehicleDao implements VehicleDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
public void insert(Vehicle vehicle) {
+ "VALUES (?, ?, ?, ?)";
Connection conn = null;
Search WWH ::

Custom Search