Reputation: 4827
I find this form of the query very convenient for returning a single value/single row from a database call, and I am fine with it throwing an exception if there is something wrong. But I have it in my head that doing a cast is generally a bad practice.
Is the cast here frowned upon?
String name = (String)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, String.class);
Upvotes: 0
Views: 3022
Reputation: 691695
You shouldn't have to cast if you're using a recent version of Spring, since it's a generic method and the signature of the method is now:
public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException
If you're using an old version, then either cast, or upgrade to a recent version.
Upvotes: 0
Reputation: 35008
Since Spring 3.1, the JdbcTemplate can use generics and varargs with queryForObject:
String name = getJdbcTemplate().queryForObject(sql, String.class, custId);
Prior to Spring 3.1, this was available through getSimpleJdbcTemplate()
String name = getSimpleJdbcTemplate().queryForObject(sql, String.class, custId);
EDIT:
This requires JDK 1.5 or higher.
Upvotes: 1