In my UserDao I want to return a list of users.
I already have a UserRowMapper
that implements RowMapper<User>
.
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<User> users = new ArrayList<User>();
?
RowMapper<T> interface is used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object. SQLExceptions if any thrown will be caught and handled by the calling JdbcTemplate.
It defines only one method mapRow that accepts ResultSet instance and int as the parameter list. Syntax of the method is given below: public T mapRow(ResultSet rs, int rowNumber)throws SQLException.
The JdbcTemplate query method is overloaded and provides a method that accepts three parameters consisting of an SQL string to select based on ID, a RowMapper to map the returned row to an object, and an id to be bound to the query.
Use JdbcTemplate.query(String sql, RowMapper<T> rowMapper, Object... args)
, and you can pass in a variable number of values for the ?
placeholders as the last argument(s):
public List<User> findById(int userId)
{
return getJdbcTemplate().query(
"SELECT * FROM users WHERE user_id=?",
new UserRowMapper(),
userId
);
}
Or something like:
public List<User> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With