Java Reference
In-Depth Information
The org.springframework.jdbc.core.JdbcTemplate class declares a number of overloaded update()
template methods to control the overall update process. Different versions of the update() method allow
you to override different task subsets of the default process. The Spring JDBC framework predefines
several callback interfaces to encapsulate different task subsets. You can implement one of these
callback interfaces and pass its instance to the corresponding update() method to complete the process.
How It Works
Updating a Database with a Statement Creator
The first callback interface to introduce is PreparedStatementCreator . You implement this interface to
override the statement creation task (task 2) and the parameter binding task (task 3) of the overall
update process. To insert a vehicle into the database, you implement the PreparedStatementCreator
interface as follows:
package com.apress.springenterpriserecipes.vehicle;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.PreparedStatementCreator;
public class InsertVehicleStatementCreator implements PreparedStatementCreator {
private Vehicle vehicle;
public InsertVehicleStatementCreator(Vehicle vehicle) {
this.vehicle = vehicle;
public PreparedStatement createPreparedStatement(Connection conn)
throws SQLException {
+ "VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, vehicle.getVehicleNo());
ps.setString(2, vehicle.getColor());
ps.setInt(3, vehicle.getWheel());
ps.setInt(4, vehicle.getSeat());
return ps;
When implementing the PreparedStatementCreator interface, you will get the database connection
as the createPreparedStatement() method's argument. All you have to do in this method is to create a
PreparedStatement object on this connection and bind your parameters to this object. Finally, you have
to return the PreparedStatement object as the method's return value. Notice that the method signature
declares throwing SQLException , which means that you don't need to handle this kind of exception
Search WWH ::

Custom Search