Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.