Java Reference
In-Depth Information
Solution
The JdbcTemplate class declares a number of overloaded query() template methods to control the
overall query process. You can override the statement creation task (task 2) and the parameter binding
task (task 3) by implementing the PreparedStatementCreator and PreparedStatementSetter interfaces,
just as you did for the update operations. Moreover, the Spring JDBC framework supports multiple ways
for you to override the data extraction task (task 6).
How It Works
Extracting Data with a Row Callback Handler
RowCallbackHandler is the primary interface that allows you to process the current row of the result set.
One of the query() methods iterates the result set for you and calls your RowCallbackHandler for each
row. So, the processRow() method will be called once for each row of the returned result set.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
public class JdbcVehicleDao implements VehicleDao {
...
public Vehicle findByVehicleNo(String vehicleNo) {
String sql = "SELECT * FROM VEHICLE WHERE VEHICLE_NO = ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
final Vehicle vehicle = new Vehicle();
jdbcTemplate. query(sql, new Object[] { vehicleNo },
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
vehicle.setVehicleNo(rs.getString("VEHICLE_NO"));
vehicle.setColor(rs.getString("COLOR"));
vehicle.setWheel(rs.getInt("WHEEL"));
vehicle.setSeat(rs.getInt("SEAT"));
}
});
return vehicle;
}
}
As there will be one row returned for the SQL query at maximum, you can create a vehicle object
as a local variable and set its properties by extracting data from the result set. For a result set with more
than one row, you should collect the objects as a list.
Extracting Data with a Row Mapper
The RowMapper<T> interface is more general than RowCallbackHandler . Its purpose is to map a single
row of the result set to a customized object, so it can be applied to a single-row result set as well as a
multiple-row result set. From the viewpoint of reuse, it's better to implement the RowMapper interface as
a normal class than as an inner class. In the mapRow() method of this interface, you have to construct the
object that represents a row and return it as the method's return value.
Search WWH ::




Custom Search