Retrieving a list of objects
In this recipe, we will add a DAO method to retrieve database rows and create a list of objects from them.
How to do it…
Perform an SQL select
query and generate a list of objects from the result using RowMapper
:
public List<User> findAll() { String sql = "select * from user"; List<User> userList = jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class)); return userList; }
How it works…
The query()
method uses RowMapper
to generate objects from the returned database rows.
We used a ParameterizedBeanPropertyRowMapper
class assuming that the database table columns match the object attributes; however, as in the previous recipe, a custom RowMapper
interface can be used.