In my UserDao I want to return a list of users.
I already have a UserRowMapper that implements RowMapper.
How can I do this?
I tried:
List rows = getJdbcTemplate().queryforList("select * from users");
for(Map row : rows) {
}
But wasn't sure how to use my UserRowMapper to populate a User object and insert it into my list of users List.
BTW, is this the best generic list I shoudl be using:
List users = new ArrayList();
?
解决方案
Use JdbcTemplate.query(String sql, RowMapper rowMapper, Object... args), and you can pass in a variable number of values for the ? placeholders as the last argument(s):
public List findById(int userId)
{
return getJdbcTemplate().query(
"SELECT * FROM users WHERE user_id=?",
new UserRowMapper(),
userId
);
}
Or something like:
public List findByManyParams(int param1, int param2, String param3)
{
return getJdbcTemplate().query(
"SELECT * FROM users WHERE foo=? AND bar=? AND foobar=?",
new UserRowMapper(),
param1,
param2,
param3
);
}
The query() method is actually overloaded many times over, so you can usually find at least one flavor that works for what you need in any given situation.