Blankman Blankman - 1 year ago 86
Java Question

Return a list, I already have a rowmapper implementation

In my UserDao I want to return a list of users.

I already have a

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>();


Answer Source

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(),

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(),

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.