Java Reference
In-Depth Information
Now you can use this statement creator to simplify the vehicle insert operation. First of all, you have
to create an instance of the JdbcTemplate class and pass in the data source for this template to obtain a
connection from it. Then you just make a call to the update() method and pass in your statement creator
for the template to complete the update process.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcVehicleDao implements VehicleDao {
...
public void insert(Vehicle vehicle) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(new InsertVehicleStatementCreator(vehicle));
}
}
Typically, it is better to implement the PreparedStatementCreator interface and other callback
interfaces as inner classes if they are used within one method only. This is because you can get access
to the local variables and method arguments directly from the inner class, instead of passing them as
constructor arguments. The only constraint on such variables and arguments is that they must be
declared as final .
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
public class JdbcVehicleDao implements VehicleDao {
...
public void insert( final Vehicle vehicle) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update( new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn)
throws SQLException {
String sql = "INSERT INTO VEHICLE "
+ "(VEHICLE_NO, COLOR, WHEEL, SEAT) "
+ "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;
}
});
}
}
Search WWH ::




Custom Search