liveBook · Manning

Query method

As explained in Spring in Action, Sixth Edition

The JdbcTemplate query method executes a SQL query and maps its result rows to objects, optionally using parameter values.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains SQL, row mapping, parameter binding, method references, and explicit RowMapper alternatives.
Examples
Uses Ingredient queries that map id, name, and type columns, including an id-filtered lookup.
What it assumes
Assumes Java and SQL basics while demonstrating RowMapper usage and parameter values through repository code.
What you can do after
Apply it via JdbcTemplate to retrieve rows and convert them into domain objects.
How it connects
Connects JdbcTemplate with RowMapper, SQL parameters, repositories, Optional, and queryForObject.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.