JdbcTemplate中有两个可能会混淆的queryForObject方法:
1. Object queryForObject(String sql, Object[] args, Class requiredType)
2. Object queryForObject(String sql, Object[] args, RowMapper rowMapper)
第1个方法是只查一列的,参数“requiredType”不可以是自定义的类 如果要把查询结果封装为自定义的类,需要采用第2个方法 例如:
//只查询一列:name
String sql = "SELECT NAME FROM CUSTOMER WHERE CUST_ID = ?";
String name = (String)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, String.class);
return name;
//查询返回自定义的类
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";
Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId },
new BeanPropertyRowMapper(Customer.class));
return customer;