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.
AthleteAthleteControllerRawJdbcAthleteDaoDataSourceH2

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:

  1. Ask the DataSource for a connection.
  2. Prepare the statement and bind the parameter.
  3. Execute and iterate the ResultSet.
  4. Close everything, also when something fails.
  5. 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 with schema.sql and data.sql) and a ready-to-inject JdbcTemplate.
  • queryForObject(sql, Integer.class) returns one value from one row: the COUNT(*).
  • 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 a List<Athlete>.
  • queryForObject(sql, ATHLETE, id) returns a single Athlete.
  • Without a mapper, queryForList(sql) returns a List<Map<String, Object>> (column → value) and queryForMap(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 a PreparedStatementCreator with RETURN_GENERATED_KEYS and a KeyHolder.
  • 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.

Cheatsheet →

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
}

Quiz

1. What happens with jdbc.queryForObject("SELECT name FROM athlete WHERE id = ?", String.class, 99) if there's no athlete with id 99?

2. You need to go through all rows to build a single Map with each athlete's best time. Which callback fits best?

3. What does jdbc.update("UPDATE athlete SET division = ? WHERE division = ?", "RX", "SCALED") return?

4. You insert an athlete whose name already exists and the column is UNIQUE. What exception do you see when using JdbcTemplate?

5. What's the difference between RowMapper and RowCallbackHandler?

6. Which statement about JdbcTemplate is correct?

Cheatsheet → · Mock exam →

Run it