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
:
In the DAO class, add an inline class implementing
RowMapper
. This class defines how to generate aUser
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; } }
Add a DAO method which will perform an SQL
select
query and use aUserMapper
object to generate aUser
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...