Java Reference
In-Depth Information
// No need to cast into String anymore.
String color = getSimpleJdbcTemplate().queryForObject(sql,
String.class, vehicleNo);
return color;
}
}
3-5. Using Named Parameters in a JDBC Template
Problem
In classic JDBC usage, SQL parameters are represented by the placeholder ? and are bound by position.
The trouble with positional parameters is that whenever the parameter order is changed, you have
to change the parameter bindings as well. For a SQL statement with many parameters, it is very
cumbersome to match the parameters by position.
Solution
Another option when binding SQL parameters in the Spring JDBC framework is to use named
parameters. As the term implies, named SQL parameters are specified by name (starting with a colon)
rather than by position. Named parameters are easier to maintain and also improve readability. At
runtime, the framework classes replace named parameters with placeholders. Named parameters are
supported only in SimpleJdbcTemplate and NamedParameterJdbcTemplate .
How It Works
When using named parameters in your SQL statement, you can provide the parameter values in a map
with the parameter names as the keys.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcVehicleDao extends SimpleJdbcDaoSupport implements
VehicleDao {
public void insert(Vehicle vehicle) {
String sql = "INSERT INTO VEHICLE (VEHICLE_NO, COLOR, WHEEL, SEAT) "
+ "VALUES ( :vehicleNo, :color, :wheel, :seat)";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("vehicleNo", vehicle.getVehicleNo());
parameters.put("color", vehicle.getColor());
parameters.put("wheel", vehicle.getWheel());
parameters.put("seat", vehicle.getSeat());
getSimpleJdbcTemplate().update(sql, parameters);
}
...
}
 
Search WWH ::




Custom Search