Java Reference
In-Depth Information
To query for a single string value, you can call the overloaded
queryForObject()
method, which
requires an argument of
java.lang.Class
type. This method will help you to map the result value to the
type you specified. For integer values, you can call the convenient method
queryForInt()
.
package com.apress.springenterpriserecipes.vehicle;
...
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcVehicleDao implements VehicleDao {
...
public String getColor(String vehicleNo) {
String sql = "SELECT COLOR FROM VEHICLE WHERE VEHICLE_NO = ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String color = (String) jdbcTemplate.
queryForObject(sql,
new Object[] { vehicleNo },
String.class);
return color;
}
public int countAll() {
String sql = "SELECT COUNT(*) FROM VEHICLE";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.
queryForInt(sql);
return count;
}
}
You can test these two methods with the following code snippet in the
Main
class:
package com.apress.springenterpriserecipes.vehicle;
...
public class Main {
public static void main(String[] args) {
...
VehicleDao vehicleDao = (VehicleDao) context.getBean("vehicleDao");
int count = vehicleDao.countAll();
System.out.println("Vehicle Count: " + count);
String color = vehicleDao.getColor("TEM0001");
System.out.println("Color for [TEM0001]: " + color);
}
}
Search WWH ::
Custom Search