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 an object


In this recipe, we create a DAO method to retrieve a database row, which we will use to create an object.

How to do it…

Use an SQL select query and create an object from the result using RowMapper:

  1. In the DAO class, add an inline class implementing RowMapper. This class defines how to generate a User object from a database row:

    private class UserMapper implements RowMapper<User> {
      public User mapRow(ResultSet row, int rowNum) throws SQLException {
        User user = new User();
    
        user.setId(row.getLong("id"));
        user.setFirstName(row.getString("first_name"));
        user.setAge(row.getInt("age"));
        
        return user;
      }
    }
  2. Add a DAO method which will perform an SQL select query and use a UserMapper object to generate a User object:

    public User findById(Long id) {
      String sql = "select * from user where id=?";
      User user = jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserMapper());
      return user;
    }

How it works…

The queryForObject() method uses the UserMapper...