Cheatsheet

JdbcTemplate

Key idea

`JdbcTemplate` applies the Template Method pattern to JDBC: it opens and closes the connection, prepares the statement, iterates the result and translates exceptions. You only provide the SQL, the parameters and, when needed, a callback that turns rows into objects.

Diagram (UML)

ApplicationContextAthleteAthleteControllerAthleteRepositoryJdbcTemplateDataSourceH2RowMapperRowCallbackHandler

Key pieces

  • JdbcTemplate(DataSource): thread-safe, created once and shared (Spring Boot auto-configures it)
  • queryForObject(sql, Class, args…) / queryForObject(sql, RowMapper, args…): exactly one row
  • query(sql, RowMapper, args…) → List<T>; queryForList(sql) → List<Map<String, Object>>; queryForMap(sql) → Map
  • update(sql, args…) → affected rows (INSERT, UPDATE, DELETE); batchUpdate(…); KeyHolder for generated keys
  • Callbacks: RowMapper<T> (row → object), RowCallbackHandler (row → nothing), ResultSetExtractor<T> (whole result → one object)
  • NamedParameterJdbcTemplate: :name parameters and lists in IN (:list)

AthleteRepository.java

private static final RowMapper<Athlete> ATHLETE = (rs, rowNum) ->              // one row → one object
    new Athlete(rs.getLong("id"), rs.getString("name"), rs.getString("division"));

public List<Athlete> findByDivision(String division) {
    return jdbc.query("SELECT * FROM athlete WHERE division = ? ORDER BY name", ATHLETE, division);
}

public Optional<Athlete> findById(long id) {
    return jdbc.query("SELECT * FROM athlete WHERE id = ?", ATHLETE, id).stream().findFirst();
}

public List<Map<String, Object>> rawRows() {
    return jdbc.queryForList("SELECT name, division FROM athlete ORDER BY id"); // no mapper: maps
}

Remember for the exam

  • JdbcTemplate handles the connection, statement, ResultSet, resource closing and exceptions; you don't write try/finally
  • Parameters go as ? and are passed as varargs: it protects against SQL injection
  • RowMapper and RowCallbackHandler: Spring iterates and calls you per row. ResultSetExtractor: you iterate with rs.next()
  • SQLExceptions (checked, vendor-specific) are translated into the DataAccessException hierarchy (unchecked, vendor-neutral)
  • Examples from the hierarchy: DuplicateKeyException, BadSqlGrammarException, EmptyResultDataAccessException, DataIntegrityViolationException
  • JdbcClient (Spring 6.1+) is a fluent API on top of the same templates

Exam traps

  • queryForObject with 0 rows throws EmptyResultDataAccessException; with more than 1, IncorrectResultSizeDataAccessException. It never returns null for "not found"
  • queryForList(sql, String.class) is for a single column; for several columns use a RowMapper or queryForList(sql) (maps)
  • update() returns an int (affected rows), not the generated key; for the key you need a KeyHolder
  • DataAccessException is unchecked: you aren't forced to catch it

← JdbcTemplate · Run it