Java Reference
In-Depth Information
Running the DAO
The following Main class tests your DAO by using it to insert a new vehicle to the database. If it succeeds,
you can query the vehicle from the database immediately.
package com.apress.springenterpriserecipes.vehicle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
VehicleDao vehicleDao = (VehicleDao) context.getBean("vehicleDao");
Vehicle vehicle = new Vehicle("TEM0001", "Red", 4, 4);
vehicleDao.insert(vehicle);
vehicle = vehicleDao.findByVehicleNo("TEM0001");
System.out.println("Vehicle No: " + vehicle.getVehicleNo());
System.out.println("Color: " + vehicle.getColor());
System.out.println("Wheel: " + vehicle.getWheel());
System.out.println("Seat: " + vehicle.getSeat());
}
}
Now you can implement a DAO using JDBC directly. However, as you can see from the preceding
DAO implementation, most of the JDBC code is similar and needs to be repeated for each database
operation. Such redundant code will make your DAO methods much longer and less readable.
3-1. Using a JDBC Template to Update a Database
Problem
To implement a JDBC update operation, you have to perform the following tasks, most of which are
redundant:
1.
Obtain a database connection from the data source.
Create a PreparedStatement object from the connection.
2.
3.
Bind the parameters to the PreparedStatement object.
Execute the PreparedStatement object.
4.
Handle SQLException .
5.
Clean up the statement object and connection.
6.
 
Search WWH ::




Custom Search