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