Video in progress
Which pattern do the "Template" names in `JdbcTemplate`, `RestTemplate` and `TransactionTemplate` come from, and how do they work?
It's the Template Method idea, but done with a callback instead of inheritance: the template handles the fixed part (opening and closing the resource, translating exceptions), and you supply only the variable step as a lambda.
📖 Answer
With plain JDBC, every query has the same "ritual": get a connection, prepare a statement, loop over the ResultSet, close everything in finally, catch SQLException. The only really useful part is the SQL and turning a row into an object.
JdbcTemplate takes the ritual on itself:
List<Course> list = jdbc.query(
"select id, title from course where price < ?",
(rs, rowNum) -> new Course(rs.getLong("id"), rs.getString("title")),
100_000
);
RowMapper is the callback. Inside the template the skeleton is fixed: acquire the resource → your callback → close the resource → translate SQLException into Spring's DataAccessException hierarchy.
The classic Template Method in GoF works with an abstract class and a subclass. Spring chose callbacks instead of inheritance, because writing a new subclass for every query would be awkward. Sometimes this is given its own name, "Template Callback".
TransactionTemplate.execute(status -> ...) is the same: the begin/commit/rollback skeleton is ready, and you provide the inner work. It's handy where you can't use @Transactional (for example, several short transactions inside one method).
Good to know: for new code, Spring 6.1+ recommends RestClient instead of RestTemplate, which is in maintenance mode.
Sign up to mark studied questions and save your progress.