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)
classDiagram
direction LR
class AthleteRepository {
<<@Repository>>
+count() int
+findByDivision(String) List~Athlete~
+add(name, division) long
}
class JdbcTemplate {
<<template>>
+queryForObject(sql, Class, args) T
+query(sql, RowMapper, args) List~T~
+query(sql, ResultSetExtractor, args) T
+query(sql, RowCallbackHandler, args) void
+update(sql, args) int
}
class RowMapper {
<<callback>>
+mapRow(ResultSet, int) T
}
class ResultSetExtractor {
<<callback>>
+extractData(ResultSet) T
}
class RowCallbackHandler {
<<callback>>
+processRow(ResultSet) void
}
class DataAccessException {
<<unchecked>>
}
AthleteRepository --> JdbcTemplate
JdbcTemplate --> DataSource
JdbcTemplate ..> RowMapper : calls per row
JdbcTemplate ..> ResultSetExtractor : calls once
JdbcTemplate ..> RowCallbackHandler : calls per row
JdbcTemplate ..> DataAccessException : translates SQLException
DataAccessException <|-- DuplicateKeyException
DataAccessException <|-- IncorrectResultSizeDataAccessException
IncorrectResultSizeDataAccessException <|-- EmptyResultDataAccessExceptionKey pieces
JdbcTemplate(DataSource): thread-safe, created once and shared (Spring Boot auto-configures it)queryForObject(sql, Class, args…)/queryForObject(sql, RowMapper, args…): exactly one rowquery(sql, RowMapper, args…)→List<T>;queryForList(sql)→List<Map<String, Object>>;queryForMap(sql)→Mapupdate(sql, args…)→ affected rows (INSERT, UPDATE, DELETE);batchUpdate(…);KeyHolderfor generated keys- Callbacks:
RowMapper<T>(row → object),RowCallbackHandler(row → nothing),ResultSetExtractor<T>(whole result → one object) NamedParameterJdbcTemplate::nameparameters and lists inIN (: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
JdbcTemplatehandles the connection, statement,ResultSet, resource closing and exceptions; you don't writetry/finally- Parameters go as
?and are passed as varargs: it protects against SQL injection RowMapperandRowCallbackHandler: Spring iterates and calls you per row.ResultSetExtractor: you iterate withrs.next()SQLExceptions (checked, vendor-specific) are translated into theDataAccessExceptionhierarchy (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
queryForObjectwith 0 rows throwsEmptyResultDataAccessException; with more than 1,IncorrectResultSizeDataAccessException. It never returnsnullfor "not found"queryForList(sql, String.class)is for a single column; for several columns use aRowMapperorqueryForList(sql)(maps)update()returns anint(affected rows), not the generated key; for the key you need aKeyHolderDataAccessExceptionis unchecked: you aren't forced to catch it