Java Reference
In-Depth Information
public class JdbcVehicleDao extends SimpleJdbcDaoSupport implements
VehicleDao {
...
public Vehicle findByVehicleNo(String vehicleNo) {
String sql = "SELECT * FROM VEHICLE WHERE VEHICLE_NO = ?";
Vehicle vehicle = getSimpleJdbcTemplate().queryForObject(sql,
ParameterizedBeanPropertyRowMapper.newInstance(Vehicle.class),
vehicleNo);
return vehicle;
}
}
When using the classic JdbcTemplate , the findAll() method has a warning from the Java compiler
because of an unchecked conversion from List to List<Vehicle> . This is because the return type of the
query() method is List rather than the type-safe List<Vehicle> . After switching to SimpleJdbcTemplate
and ParameterizedBeanPropertyRowMapper<T> , the warning will be eliminated immediately because the
returned List is parameterized with the same type as the ParameterizedRowMapper<T> argument.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcVehicleDao extends SimpleJdbcDaoSupport implements
VehicleDao {
...
public List<Vehicle> findAll() {
String sql = "SELECT * FROM VEHICLE";
List<Vehicle> vehicles = getSimpleJdbcTemplate().query(sql,
ParameterizedBeanPropertyRowMapper.newInstance(Vehicle.class));
return vehicles;
}
}
When querying for a single value with SimpleJdbcTemplate , the return type of the queryForObject()
method will be determined by the class argument (e.g., String.class ). So, there's no need for you to
perform type casting manually. Note that the statement parameters of variable length must also be
supplied at the end of the argument list.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcVehicleDao extends SimpleJdbcDaoSupport implements
VehicleDao {
...
public String getColor(String vehicleNo) {
String sql = "SELECT COLOR FROM VEHICLE WHERE VEHICLE_NO = ?";
Search WWH ::




Custom Search