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 ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.