Java Reference
In-Depth Information
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
public class VehicleRowMapper implements ParameterizedRowMapper<Vehicle> {
public Vehicle mapRow(ResultSet rs, int rowNum) throws SQLException {
Vehicle vehicle = new Vehicle();
vehicle.setVehicleNo(rs.getString("VEHICLE_NO"));
vehicle.setColor(rs.getString("COLOR"));
vehicle.setWheel(rs.getInt("WHEEL"));
vehicle.setSeat(rs.getInt("SEAT"));
return vehicle;
}
}
Using SimpleJdbcTemplate with ParameterizedRowMapper<T> can save you the trouble of casting the
type of the returned result. For the queryForObject() method, the return type is determined by the
ParameterizedRowMapper<T> object's type parameter, which is Vehicle in this case. Note that the
statement parameters must be supplied at the end of the argument list since they are of variable length.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcVehicleDao extends SimpleJdbcDaoSupport implements
VehicleDao {
...
public Vehicle findByVehicleNo(String vehicleNo) {
String sql = "SELECT * FROM VEHICLE WHERE VEHICLE_NO = ?";
// No need to cast into Vehicle anymore.
Vehicle vehicle = getSimpleJdbcTemplate().queryForObject(sql,
new VehicleRowMapper(), vehicleNo);
return vehicle;
}
}
Spring also comes with a convenient ParameterizedRowMapper<T> implementation,
ParameterizedBeanPropertyRowMapper<T>, which can automatically map a row to a new
instance of the specified class.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
Search WWH ::




Custom Search