Skip to lesson

Template classes: JdbcTemplate and RestClient

Every ShopLite JDBC query repeats the same steps: connect, prepare, loop over rows, close and handle errors. Only the SQL and how a row becomes an object change. Repeating the rest everywhere is slow and error-prone.

Boilerplate JDBC steps vs JdbcTemplate

JdbcTemplate is a Spring class that performs the fixed JDBC steps and lets you supply only the SQL, the parameters and a row mapping.

With plain JDBC, each query needs about 15 lines. With JdbcTemplate, the same query is one call, and the only custom part is the RowMapper.

ProductRepository.javaJava
@Repositorypublic class ProductRepository {    private final JdbcTemplate jdbc;
    public ProductRepository(JdbcTemplate jdbc) { this.jdbc = jdbc; }
    public List<Product> findCheaperThan(BigDecimal limit) {        return jdbc.query(                "SELECT id, name, price FROM product WHERE price < ? ORDER BY price",                (rs, rowNum) -> new Product(rs.getInt("id"), rs.getString("name"),                        rs.getBigDecimal("price")),       // RowMapper: the only custom part                limit);    }}

Plain JDBC needs getConnection, prepareStatement, setBigDecimal, executeQuery, a while (rs.next()) loop, try-with-resources for three objects and a catch for SQLException. Code repeated almost unchanged like this is called boilerplate. JdbcTemplate also turns the checked SQLException into Spring's unchecked DataAccessException.

Order of execution

What jdbc.query does for you

Tap the steps in the order the template runs them.

Callbacks: RowMapper as the custom detail

A callback is a piece of code you hand to another method so that method can call it at the right moment.

RowMapper<T> is the callback of JdbcTemplate: its one method mapRow(rs, rowNum) turns the current row into a T. A plain Java model makes the split easy to see.

Example 1 · A mini JdbcTemplate with a RowMapper callback

MiniTemplateDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;
// A row from our pretend databaseinterface Row {    String getString(String column);    int getInt(String column);}
// The callback: the only part the caller writesinterface RowMapper<T> {    T mapRow(Row row, int rowNum);}
// The template: fixed steps in a fixed order, details from the callbackclass MiniJdbcTemplate {    private final List<Map<String, Object>> table;
    MiniJdbcTemplate(List<Map<String, Object>> table) {        this.table = table;    }
    <T> List<T> query(String sql, RowMapper<T> mapper) {        System.out.println("  open connection");        System.out.println("  run: " + sql);        List<T> results = new ArrayList<>();        try {            int rowNum = 0;            for (Map<String, Object> data : table) {                Row row = new Row() {                    public String getString(String c) { return (String) data.get(c); }                    public int getInt(String c) { return (Integer) data.get(c); }                };                results.add(mapper.mapRow(row, rowNum++));            }        } finally {            System.out.println("  close connection");        }        return results;    }}
record Product(int id, String name, int price) { }
public class MiniTemplateDemo {    public static void main(String[] args) {        MiniJdbcTemplate jdbc = new MiniJdbcTemplate(List.of(                Map.of("id", 1, "name", "Earbuds", "price", 1499),                Map.of("id", 2, "name", "Notebook", "price", 60)));
        System.out.println("Products:");        List<Product> products = jdbc.query("SELECT id, name, price FROM product",                (row, n) -> new Product(row.getInt("id"), row.getString("name"), row.getInt("price")));        System.out.println(products);
        System.out.println("Names only:");        List<String> names = jdbc.query("SELECT name FROM product",                (row, n) -> (n + 1) + ". " + row.getString("name"));        System.out.println(names);    }}
Output
Products:
  open connection
  run: SELECT id, name, price FROM product
  close connection
[Product[id=1, name=Earbuds, price=1499], Product[id=2, name=Notebook, price=60]]
Names only:
  open connection
  run: SELECT name FROM product
  close connection
[1. Earbuds, 2. Notebook]

What this code does

  • MiniJdbcTemplate.query owns the fixed steps: open, run, loop, close. The lambdas are RowMappers and decide only how one row becomes a result.
  • The same template serves two different queries with two different mappers, with no new class.

Example 2 · The template still cleans up when the callback fails

MapperFailsDemo.javaJava
import java.util.ArrayList;import java.util.List;
interface RowMapper<T> {    T mapRow(String[] row, int rowNum);}
class MiniJdbcTemplate {    private final List<String[]> table;
    MiniJdbcTemplate(List<String[]> table) {        this.table = table;    }
    <T> List<T> query(String sql, RowMapper<T> mapper) {        System.out.println("  open connection");        List<T> results = new ArrayList<>();        try {            int rowNum = 0;            for (String[] row : table) {                results.add(mapper.mapRow(row, rowNum++));            }            return results;        } catch (RuntimeException e) {            // Spring turns low-level errors into its own DataAccessException family            throw new IllegalStateException("Query failed: " + sql + " (" + e.getMessage() + ")", e);        } finally {            System.out.println("  close connection");        }    }}
public class MapperFailsDemo {    public static void main(String[] args) {        MiniJdbcTemplate jdbc = new MiniJdbcTemplate(List.of(                new String[] {"Earbuds", "1499"},                new String[] {"Pen set", "1.5k"}));        try {            jdbc.query("SELECT name, price FROM product",                    (row, n) -> row[0] + " Rs. " + Integer.parseInt(row[1]));        } catch (IllegalStateException e) {            System.out.println(e.getMessage());        }    }}
Output
  open connection
  close connection
Query failed: SELECT name, price FROM product (For input string: "1.5k")

What this code does

  • The mapper throws NumberFormatException on 1.5k, yet close connection is printed because the template's finally block owns the cleanup.
  • The template also wraps the low-level error in one clear exception type, as JdbcTemplate does with DataAccessException.

The template owns the loop and calls your mapper once per row. Because it also owns the try/finally, the connection is closed even when your mapper throws.

Predict the output

Predict the template

Pick what the template does.

Round 1 of 2

Row 2 holds the text 1.5k. What happens to the connection?

jdbc.query("SELECT price FROM product",
(rs, i) -> Double.parseDouble(rs.getString("price")));
// row 1 holds "40", row 2 holds "1.5k"

Template Method by callback instead of inheritance

Template Method is a pattern where a fixed skeleton of steps is written once and the steps that change are filled in by the caller: classically by a subclass, in Spring by a callback.

Two exports share one skeleton: a start line, the rows and a row count. Only the row format differs. The example solves it with inheritance and then with a callback.

Example 3 · Template Method by inheritance and by callback

InheritanceVsCallbackDemo.javaJava
import java.util.List;import java.util.function.Function;
record Order(String id, String customer, int total) { }
// Classic Template Method: the base class fixes the steps, a subclass fills one inabstract class OrderExport {    final void run(List<Order> orders) {        System.out.println("--- export start ---");        for (Order o : orders) {            System.out.println(formatRow(o));        }        System.out.println("--- " + orders.size() + " rows ---");    }
    abstract String formatRow(Order o);}
class CsvOrderExport extends OrderExport {    String formatRow(Order o) {        return o.id() + "," + o.customer() + "," + o.total();    }}
// Spring style: the same fixed steps, the detail passed in as a callbackclass ExportTemplate {    void run(List<Order> orders, Function<Order, String> formatRow) {        System.out.println("--- export start ---");        for (Order o : orders) {            System.out.println(formatRow.apply(o));        }        System.out.println("--- " + orders.size() + " rows ---");    }}
public class InheritanceVsCallbackDemo {    public static void main(String[] args) {        List<Order> orders = List.of(new Order("ORD-1", "Riya", 899), new Order("ORD-2", "Kabir", 1499));
        System.out.println("Inheritance:");        new CsvOrderExport().run(orders);
        System.out.println("Callback:");        ExportTemplate template = new ExportTemplate();        template.run(orders, o -> o.id() + "," + o.customer() + "," + o.total());        template.run(orders, o -> o.customer() + " paid Rs. " + o.total());    }}
Output
Inheritance:
--- export start ---
ORD-1,Riya,899
ORD-2,Kabir,1499
--- 2 rows ---
Callback:
--- export start ---
ORD-1,Riya,899
ORD-2,Kabir,1499
--- 2 rows ---
--- export start ---
Riya paid Rs. 899
Kabir paid Rs. 1499
--- 2 rows ---

What this code does

  • OrderExport.run is a classic template method: a fixed skeleton calling the abstract formatRow, filled in by CsvOrderExport.
  • ExportTemplate.run has the same skeleton but takes formatRow as a Function. The second format needs a lambda, not a new subclass.

Classically, the skeleton is a final method of an abstract class and subclasses fill in the abstract steps. Spring's templates keep the skeleton but take the details as callback objects instead of subclasses.

Callbacks are lighter: one template object serves many queries, each detail can be a lambda, and you choose it per call at runtime. Inheritance is still fine when the subclass has several related steps and its own state.

RestClient's fluent API: builder plus template

RestClient is Spring's synchronous HTTP client with a fluent API (Spring Framework 6.1 and later).

RestClient.builder() is a Builder for the shared settings. Each call then follows the template idea: the client does the HTTP steps, and you supply the URI, the target type and error callbacks.

Java
RestClient client = builder                           // Builder: configure once        .baseUrl("https://payments.example.com")        .defaultHeader("Accept", "application/json")        .build();
PaymentStatus status = client.get()                   // template: fixed HTTP steps        .uri("/v1/payments/{id}", paymentId)        .retrieve()        .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {            throw new PaymentNotFoundException(paymentId);   // callback for errors        })        .body(PaymentStatus.class);                    // JSON converted to an object

The client opens the connection, writes the request, reads the response, converts JSON and handles errors. In Spring Boot you inject the ready RestClient.Builder bean, configure it once in a constructor and keep the built client in a field.

Order of execution

What the client call does

Tap the steps in the order they happen.

RestTemplate, the older client with the same template idea, still works but new code should use RestClient.

Writing a tiny RetryTemplate in plain Java

A retry template runs an action and, if it fails, tries again up to a set number of attempts. The loop and the give-up rule are fixed; the action is a callback.

ShopLite's payment gateway sometimes times out. A small retry template wraps the call in a loop and gives up after a set number of attempts.

Example 4 · A tiny RetryTemplate

RetryTemplateDemo.javaJava
import java.util.concurrent.Callable;
class RetryTemplate {    private final int maxAttempts;
    RetryTemplate(int maxAttempts) {        this.maxAttempts = maxAttempts;    }
    <T> T execute(Callable<T> action) throws Exception {        Exception last = null;        for (int attempt = 1; attempt <= maxAttempts; attempt++) {            try {                T result = action.call();                System.out.println("  attempt " + attempt + ": ok");                return result;            } catch (Exception e) {                System.out.println("  attempt " + attempt + ": " + e.getMessage());                last = e;            }        }        throw last;    }}
// A payment gateway that times out a few times before it answersclass FlakyPaymentGateway {    private int failuresLeft;
    FlakyPaymentGateway(int failures) {        this.failuresLeft = failures;    }
    String charge(String orderId) {        if (failuresLeft > 0) {            failuresLeft--;            throw new IllegalStateException("gateway timeout");        }        return orderId + " paid";    }}
public class RetryTemplateDemo {    public static void main(String[] args) {        RetryTemplate retry = new RetryTemplate(3);
        FlakyPaymentGateway twoFailures = new FlakyPaymentGateway(2);        try {            System.out.println("ORD-11:");            System.out.println("Result: " + retry.execute(() -> twoFailures.charge("ORD-11")));        } catch (Exception e) {            System.out.println("Gave up: " + e.getMessage());        }
        FlakyPaymentGateway down = new FlakyPaymentGateway(5);        try {            System.out.println("ORD-12:");            System.out.println("Result: " + retry.execute(() -> down.charge("ORD-12")));        } catch (Exception e) {            System.out.println("Gave up: " + e.getMessage());        }    }}
Output
ORD-11:
  attempt 1: gateway timeout
  attempt 2: gateway timeout
  attempt 3: ok
Result: ORD-11 paid
ORD-12:
  attempt 1: gateway timeout
  attempt 2: gateway timeout
  attempt 3: gateway timeout
Gave up: gateway timeout

What this code does

  • execute is the fixed retry loop; the lambda passed in is the action. ORD-11 succeeds on attempt 3 after two timeouts.
  • ORD-12 fails all 3 attempts, so the template gives up and rethrows the last exception for the caller to handle.

The action is a Callable<T> (a task that returns a value and may throw). Spring offers ready retry support (the Spring Retry library, and a built-in RetryTemplate in Spring Framework 7), but a small one shows how little magic is involved.

Predict the output

Predict the retries

Pick what the retry template does.

Round 1 of 2

What happens when the gateway times out twice and then answers?

RetryTemplate retry = new RetryTemplate(3);
String result = retry.execute(() -> gateway.charge(order));
// timeout, timeout, then "paid"
Retry only failures that can pass on their own, such as a timeout. Retrying a declined card or a bad request only repeats the same error, and retrying a charge needs an idempotency key so the customer is not charged twice.

Next step

Check your understanding

12 quick questions