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.
- In the box
- Reading an athlete's name with plain JDBC took fifteen lines of plumbing. JdbcTemplate keeps the plumbing and leaves you the SQL and the mapping. Learn its query methods, the three kinds of callback and how it translates exceptions.
The controller calls findName() on RawJdbcAthleteDao, highlighted in red, which asks the DataSource for getConnection(); the DataSource is connected to the H2 database.
JdbcTemplate appears, highlighted between AthleteRepository and the DataSource. The repository sends it queryForObject() and the template asks for the connection.
RowMapper appears, highlighted below JdbcTemplate, which sends it mapRow(rs, n) for each row.
The repository sends JdbcTemplate, highlighted, a query with 0 or 2 rows: queryForObject throws in both cases.
A POST athlete reaches the controller; the repository sends update() to JdbcTemplate and the INSERT row reaches the database. The repository and H2 are highlighted.
ResultSetExtractor and RowCallbackHandler, highlighted, receive extractData(rs) and processRow(rs) from JdbcTemplate.
SQLExceptionTranslator, highlighted in red, receives an SQLException from JdbcTemplate and turns it into a DataAccessException.
NamedParameterJdbcTemplate, highlighted in the template's place, receives :names from the repository.
Final view: controller, repository, JdbcTemplate, DataSource and H2 in a row, with RowMapper and RowCallbackHandler below the template.
Step 1 of 9
Fifteen lines to read a name
RawJdbcAthleteDao reads an athlete's name with plain JDBC. The query is one line; the rest is plumbing:
- Ask the
DataSourcefor a connection. - Prepare the statement and bind the parameter.
- Execute and iterate the
ResultSet. - Close everything, also when something fails.
- Catch the
SQLException, which is checked and vendor-specific too.
Step 2 of 9
JdbcTemplate: you write the SQL
JdbcTemplate is the Template Method pattern applied to JDBC: the fixed algorithm (connection, statement, execution, closing, exceptions) is its job; the variable part (SQL, parameters, mapping) is yours.
- Spring Boot creates the
DataSource(here an in-memory H2 initialized withschema.sqlanddata.sql) and a ready-to-injectJdbcTemplate. queryForObject(sql, Integer.class)returns one value from one row: theCOUNT(*).- Parameters go as
?and are passed at the end, as varargs. Never concatenate values into the SQL.
Step 3 of 9
RowMapper: from row to object
For whole rows, you give a RowMapper<T>: a (rs, rowNum) -> T function that turns the current row into an object. Spring iterates the result and calls you once per row.
query(sql, ATHLETE, "RX")returns aList<Athlete>.queryForObject(sql, ATHLETE, id)returns a singleAthlete.- Without a mapper,
queryForList(sql)returns aList<Map<String, Object>>(column → value) andqueryForMap(sql), a single map.
Step 4 of 9
Trap: queryForObject wants exactly one row
queryForObject promises exactly one row:
- 0 rows →
EmptyResultDataAccessException. - 2 or more →
IncorrectResultSizeDataAccessException.
It doesn't return null for "not found". That's why divisionOf() catches the exception and returns Optional.empty(), and findById() uses query(...) and keeps the first element of the list.
Step 5 of 9
update(): insert, modify, delete
To write you use update, which returns how many rows it touched:
update("UPDATE athlete SET division = ? WHERE division = ?", "RX", "SCALED")→2.- To get an
INSERT's auto-generated id, you pass aPreparedStatementCreatorwithRETURN_GENERATED_KEYSand aKeyHolder. - For many rows at once,
batchUpdate(sql, listOfArgs)sends them in a batch.
Step 6 of 9
Three callbacks, three uses
Besides RowMapper, JdbcTemplate takes two other callbacks:
| Callback | Who iterates | Returns | For |
|---|---|---|---|
RowMapper<T> |
Spring | one T per row → List<T> |
turning rows into objects |
RowCallbackHandler |
Spring | nothing (void) |
processing row by row: writing a CSV, counting… |
ResultSetExtractor<T> |
you (rs.next()) |
a single T |
aggregating the whole result into one object (a map, a tree) |
bestTimes() uses an extractor to keep each athlete's best time in a Map, and exportCsv() a callback handler that writes each row.
Step 7 of 9
Exception translation
When the database complains, JdbcTemplate catches the SQLException and translates it with an SQLExceptionTranslator, using the vendor's error codes:
- Repeated name (
UNIQUE) →DuplicateKeyException. - Malformed SQL →
BadSqlGrammarException. - Other violations →
DataIntegrityViolationException, and so on.
All of them extend DataAccessException, which is unchecked and vendor-independent. Your code isn't tied to H2, PostgreSQL or Oracle, and it isn't forced to write catch. It's the same hierarchy JPA and Spring Data use (thanks to @Repository).
Step 8 of 9
Named parameters
With many ? it's easy to get the order wrong. NamedParameterJdbcTemplate uses :name and an SqlParameterSource or a Map:
WHERE name IN (:names)with a list expands to(?, ?, …)on its own.- Spring Boot auto-configures it too.
Step 9 of 9
Recap
JdbcTemplate= Template Method over JDBC: connection, statement, iteration, closing and exceptions.- Queries:
queryForObject(exactly one row),query+RowMapper(list),queryForList/queryForMap(maps). - Writes:
update(affected rows),KeyHolder,batchUpdate. - Callbacks:
RowMapper,RowCallbackHandler,ResultSetExtractor. - Exceptions:
SQLException→DataAccessException, unchecked and neutral.
Code
RawJdbcAthleteDao.java
/** Before: plain JDBC. One line of SQL, a dozen lines of plumbing. */
public class RawJdbcAthleteDao {
private final DataSource dataSource;
public RawJdbcAthleteDao(DataSource dataSource) {
this.dataSource = dataSource;
}
public String findName(long id) {
try (Connection con = dataSource.getConnection(); // open
PreparedStatement ps = con.prepareStatement("SELECT name FROM athlete WHERE id = ?")) {
ps.setLong(1, id); // bind
try (ResultSet rs = ps.executeQuery()) { // execute
return rs.next() ? rs.getString("name") : null; // iterate + map
}
} catch (SQLException e) { // checked, vendor-specific
throw new RuntimeException("query failed", e); // translate by hand
}
}
}AthleteRepository.java
public AthleteRepository(JdbcTemplate jdbc, NamedParameterJdbcTemplate named) { // auto-configured by Boot
this.jdbc = jdbc;
this.named = named;
}
public int count() {
return jdbc.queryForObject("SELECT COUNT(*) FROM athlete", Integer.class); // one row, one column
}
public Optional<String> divisionOf(String name) {
try {
return Optional.of(jdbc.queryForObject(
"SELECT division FROM athlete WHERE name = ?", String.class, name)); // "?" placeholders
} catch (EmptyResultDataAccessException none) { // zero rows
return Optional.empty();
}
}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
}JdbcTrapsTest.java
@Test
void queryForObjectWantsExactlyOneRow() {
assertThatThrownBy(() -> jdbc.queryForObject(
"SELECT name FROM athlete WHERE division = 'MASTERS'", String.class))
.isInstanceOf(EmptyResultDataAccessException.class); // 0 rows
assertThatThrownBy(() -> jdbc.queryForObject(
"SELECT name FROM athlete WHERE division = 'RX'", String.class))
.isInstanceOf(IncorrectResultSizeDataAccessException.class); // 2 rows
}AthleteRepository.java
public long add(String name, String division) {
KeyHolder keys = new GeneratedKeyHolder();
jdbc.update(con -> {
PreparedStatement ps = con.prepareStatement(
"INSERT INTO athlete (name, division) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setString(2, division);
return ps;
}, keys);
return keys.getKey().longValue(); // the generated id
}
public int promoteAll(String from, String to) {
return jdbc.update("UPDATE athlete SET division = ? WHERE division = ?", to, from); // rows changed
}AthleteRepository.java
public Map<String, Integer> bestTimes(String wod) { // ResultSetExtractor: whole result → one object
ResultSetExtractor<Map<String, Integer>> best = rs -> {
Map<String, Integer> times = new LinkedHashMap<>();
while (rs.next()) { // YOU iterate
times.putIfAbsent(rs.getString("name"), rs.getInt("seconds"));
}
return times;
};
return jdbc.query("""
SELECT a.name, r.seconds FROM wod_result r JOIN athlete a ON a.id = r.athlete_id
WHERE r.wod = ? ORDER BY r.seconds""", best, wod);
}
public void exportCsv(PrintWriter out) { // RowCallbackHandler: returns nothing
RowCallbackHandler line = rs -> // called once per row, Spring iterates
out.println(rs.getString("name") + ";" + rs.getString("division"));
jdbc.query("SELECT name, division FROM athlete ORDER BY id", line);
}JdbcTrapsTest.java
@Test
void sqlExceptionsBecomeDataAccessExceptions() {
assertThatThrownBy(() -> athletes.add("Ana", "RX")) // UNIQUE(name) violated
.isInstanceOf(DuplicateKeyException.class)
.isInstanceOf(DataAccessException.class); // unchecked, vendor-neutral
assertThatThrownBy(() -> jdbc.queryForList("SELEC * FROM athlete"))
.isInstanceOf(BadSqlGrammarException.class);
}AthleteRepository.java
public List<Athlete> findByNames(List<String> names) {
var params = new MapSqlParameterSource("names", names); // :names expands to (?, ?, …)
return named.query("SELECT * FROM athlete WHERE name IN (:names) ORDER BY name", params, ATHLETE);
}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
}