Java Reference
In-Depth Information
package com.apress.springenterpriserecipes.vehicle;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class VehicleRowMapper implements RowMapper<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;
}
}
As mentioned, RowMapper<T> can be used for either a single-row or multiple-row result set. When
querying for a unique object like in findByVehicleNo() , you have to make a call to the queryForObject()
method of JdbcTemplate .
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcVehicleDao implements VehicleDao {
...
public Vehicle findByVehicleNo(String vehicleNo) {
String sql = "SELECT * FROM VEHICLE WHERE VEHICLE_NO = ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
Vehicle vehicle = (Vehicle) jdbcTemplate. queryForObject(sql,
new Object[] { vehicleNo }, new VehicleRowMapper());
return vehicle;
}
}
Spring comes with a convenient RowMapper implementation, BeanPropertyRowMappe<T> , which can
automatically map a row to a new instance of the specified class. Note that the specified class must be
a top-level class and must have a default or no-arg constructor. It first instantiates this class and then
maps each column value to a property by matching their names. It supports matching a property name
(e.g., vehicleNo ) to the same column name or the column name with underscores (e.g., VEHICLE_NO ).
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcVehicleDao implements VehicleDao {
...
Search WWH ::




Custom Search