JdbcTemplate.query() runs a SQL query, maps each result row into an object with a RowMapper, and returns the mapped results. Pass additional arguments when the SQL contains parameters. section 3.1.2
Finding ingredients
findAll() queries every ingredient and supplies mapRowToIngredient as a method reference. findById() adds a where clause with ?, then passes id as the parameter; the method returns the first mapped result inside Optional or Optional.empty(). section 3.1.2
Listing 3.5 Querying the database with JdbcTemplate
@Override
public Iterable<Ingredient> findAll() {
return jdbcTemplate.query(
"select id, name, type from Ingredient",
this::mapRowToIngredient);
}
@Override
public Optional<Ingredient> findById(String id) {
List<Ingredient> results = jdbcTemplate.query(
"select id, name, type from Ingredient where id=?",
this::mapRowToIngredient,
id);
return results.size() == 0 ?
Optional.empty() :
Optional.of(results.get(0));
}
private Ingredient mapRowToIngredient(ResultSet row, int rowNum)
throws SQLException {
return new Ingredient(
row.getString("id"),
row.getString("name"),
Ingredient.Type.valueOf(row.getString("type")));
}
See the complete repository implementation, including SQL statements, RowMapper method reference, parameter binding, and result conversion. section 3.1.2
