Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a list, I already have a rowmapper implementation

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

?

like image 869
Blankman Avatar asked Jan 23 '12 03:01

Blankman


People also ask

What is the purpose of RowMapper interface?

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.

What are the parameters for mapRow method?

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.

What does JdbcTemplate query return?

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.


1 Answers

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.

like image 83
The Awnry Bear Avatar answered Oct 13 '22 09:10

The Awnry Bear