Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 119 ยท Spring Framework

Spring JDBC with JdbcTemplate and JdbcClient

Learn Spring JDBC: JdbcTemplate, RowMapper and ResultSetExtractor, named parameters, SimpleJdbcInsert, batches, JdbcClient, exception translation, @Transactional.

Plain JDBC is precise but noisy. Every query repeats the same ceremony: get a connection, prepare a statement, bind parameters, execute, loop over the result set, map each row, close everything in the right order, and turn a checked SQLException into something your callers can handle. You built small helpers for this in CRUD with JDBC and The DAO and Repository Pattern. Spring JDBC is the industrial version of those helpers: you write the SQL and the mapping, and Spring does everything else.

Spring JDBC sits between raw JDBC and JPA. You still write every SQL statement yourself, so there is no hidden query generation, no lazy loading and no persistence context; it is just faster, safer JDBC. Many teams use it alongside Spring Data JPA for reports, bulk work and queries that don't fit an entity model. This lesson covers the whole module: JdbcTemplate and its three callback types, NamedParameterJdbcTemplate, SimpleJdbcInsert, batch updates, the modern fluent JdbcClient, Spring's exception translation and transactions. Spring itself can't run on this page, so the Spring code is read-only, and every mechanism is rebuilt in a runnable program on the H2 database.

Setting up a DataSource

Everything in Spring JDBC starts from a javax.sql.DataSource, usually a connection pool (Connection Pooling). In Spring Boot, add spring-boot-starter-jdbc plus a driver and configure the connection:

PROPERTIES
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.datasource.password=${DB_PASSWORD}
spring.datasource.hikari.maximum-pool-size=10

Boot then creates a HikariCP DataSource, a JdbcTemplate, a NamedParameterJdbcTemplate, a JdbcClient and a transaction manager, all ready to inject. Without Boot, you declare the same beans yourself:

Java
@Configuration
@EnableTransactionManagement
class JdbcConfig {
    @Bean
    DataSource dataSource() {
        var config = new HikariConfig();
        config.setJdbcUrl("jdbc:postgresql://localhost:5432/shop");
        config.setUsername("shop");
        config.setPassword(System.getenv("DB_PASSWORD"));
        return new HikariDataSource(config);
    }

    @Bean JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); }
    @Bean JdbcClient jdbcClient(DataSource dataSource) { return JdbcClient.create(dataSource); }
    @Bean PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new JdbcTransactionManager(dataSource);
    }
}

JdbcTemplate is thread-safe once created, so one instance is shared by all your repositories. For an embedded database such as H2, Boot also runs schema.sql and then data.sql from src/main/resources at startup. For a real database, set spring.sql.init.mode=always to enable them (in production, a migration tool like Flyway or Liquibase is the better choice). If you also use JPA, spring.jpa.defer-datasource-initialization=true runs the scripts after Hibernate has created its tables.

JdbcTemplate: SQL in, objects out

A repository built on JdbcTemplate is short:

Java
@Repository
public class JdbcBookRepository {
    private static final RowMapper<Book> BOOK = (rs, rowNum) -> new Book(
        rs.getLong("id"), rs.getString("title"), rs.getBigDecimal("price"), rs.getInt("released"));

    private final JdbcTemplate jdbc;

    public JdbcBookRepository(JdbcTemplate jdbc) { this.jdbc = jdbc; }

    public List<Book> findCheaperThan(BigDecimal max) {
        return jdbc.query("SELECT id, title, price, released FROM book WHERE price < ? ORDER BY price", BOOK, max);
    }

    public Book findById(long id) {          // throws EmptyResultDataAccessException if missing
        return jdbc.queryForObject("SELECT id, title, price, released FROM book WHERE id = ?", BOOK, id);
    }

    public int count() {
        return jdbc.queryForObject("SELECT COUNT(*) FROM book", Integer.class);
    }

    public int raisePrices(BigDecimal percent) {
        return jdbc.update("UPDATE book SET price = price * (1 + ? / 100)", percent);
    }
}

The ? parameters are always bound with a PreparedStatement, so this code is as safe from SQL injection as hand-written JDBC. The template follows the template method pattern: it owns the fixed steps, and you plug in the variable parts as callbacks. There are three kinds, for three different jobs:

Callback Signature Called Use it for
RowMapper<T> T mapRow(ResultSet rs, int rowNum) once per row; Spring calls next() one row becomes one object (the common case)
ResultSetExtractor<T> T extractData(ResultSet rs) once; you call next() many rows become one object, such as a parent with its children
RowCallbackHandler void processRow(ResultSet rs) once per row, returns nothing streaming rows somewhere: a file, a running total

The model below implements a small JdbcTemplate with all three callbacks, queryForObject, update and exception translation. Notice that query is overloaded three times and the lambda's shape picks the overload: two parameters means a RowMapper, one parameter with a return means a ResultSetExtractor, and one parameter without a return means a RowCallbackHandler. Spring's real query methods work the same way.

Java A JdbcTemplate with three callbacks and exception translation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at what the callers no longer contain: no try, no close(), no SQLException. The ResultSetExtractor built a map of authors to titles from a join, something a RowMapper can't do because it sees only one row at a time. The RowCallbackHandler processed rows without collecting them, which keeps memory flat for large exports. The four failures at the end happen on purpose, and each one arrives as a specific, unchecked exception: a missing row, a duplicate primary key, a foreign key pointing at a missing author (a plain DataIntegrityViolationException), and a misspelled table name.

Exception translation

That last point is one of Spring JDBC's biggest benefits. SQLException is checked and vague: you must dig into vendor error codes to learn whether a failure was a duplicate key or a deadlock, and the codes differ between PostgreSQL, MySQL and Oracle. Spring translates every SQLException into a subclass of the unchecked DataAccessException, using built-in tables of vendor error codes with the SQLState as a fallback. The result is a portable hierarchy:

Exception Meaning Retry?
DuplicateKeyException unique or primary key violated no; report a conflict
DataIntegrityViolationException other constraint: NOT NULL, foreign key, check no; fix the data
BadSqlGrammarException invalid SQL, unknown table or column no; a bug
EmptyResultDataAccessException queryForObject found no row no; usually "not found"
IncorrectResultSizeDataAccessException queryForObject found several rows no; a bug or missing filter
QueryTimeoutException the statement took too long maybe
CannotAcquireLockException, PessimisticLockingFailureException lock timeout or deadlock yes, often

The hierarchy splits into NonTransientDataAccessException (retrying won't help) and TransientDataAccessException (it might), which makes retry policies easy to write. Spring Data repositories and @Repository beans using JPA throw the same exceptions, so your service layer handles database errors the same way whichever technology runs underneath.

Named parameters

Positional ? markers get hard to read beyond three or four parameters, and they break silently when someone reorders a WHERE clause. NamedParameterJdbcTemplate lets you write :name instead:

Java
var params = new MapSqlParameterSource()
    .addValue("max", new BigDecimal("35"))
    .addValue("ids", List.of(1, 3, 4));

List<Book> books = namedJdbc.query("""
    SELECT id, title, price, released FROM book
    WHERE price < :max AND id IN (:ids)
    ORDER BY price""", params, BOOK);

// parameters straight from an object's properties
namedJdbc.update("INSERT INTO book (id, title, price, released) VALUES (:id, :title, :price, :year)",
    new SimplePropertySqlParameterSource(newBook));      // records and fields; BeanPropertySqlParameterSource for getters

There is no named-parameter support in JDBC itself. Spring rewrites the SQL to ? markers before preparing it and binds the values in the right order. It also expands a collection into one ? per element, which makes IN lists easy, and it knows to ignore colons inside string literals and PostgreSQL's :: casts. The model below does that rewriting.

Java Rewriting named parameters, IN lists included

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The 'Note: draft' literal kept its colon, :year was bound twice because it appears twice, and the list became IN (?, ?, ?). One caution about expansion: each list size produces a different SQL string, which means a different prepared statement for the driver to plan. For very long or very variable lists, a temporary table or a database array parameter (PostgreSQL's = ANY(?)) is often better, and most databases cap the number of parameters per statement anyway.

Inserting rows: SimpleJdbcInsert and batches

Inserts have two recurring needs: getting the generated key back, and inserting many rows quickly. Spring helps with both:

Java
// SimpleJdbcInsert reads the table's columns from database metadata once
var insertBook = new SimpleJdbcInsert(dataSource)
    .withTableName("book")
    .usingGeneratedKeyColumns("id");

Number id = insertBook.executeAndReturnKey(Map.of("title", "Quiet Queries", "price", 29.90, "released", 2022));

// a KeyHolder with JdbcTemplate
var keys = new GeneratedKeyHolder();
jdbc.update(con -> {
    var ps = con.prepareStatement("INSERT INTO book (title, price, released) VALUES (?, ?, ?)", new String[] {"id"});
    ps.setString(1, "Index Magic");
    ps.setBigDecimal(2, new BigDecimal("41.00"));
    ps.setInt(3, 2024);
    return ps;
}, keys);
long newId = keys.getKey().longValue();

// batches: one round trip per chunk instead of per row
int[] counts = jdbc.batchUpdate("UPDATE book SET price = ? WHERE id = ?",
    List.of(new Object[] {19.90, 1}, new Object[] {44.00, 2}));

int[][] chunks = jdbc.batchUpdate("INSERT INTO sale (book_id, qty) VALUES (?, ?)", sales, 1000,
    (ps, sale) -> {
        ps.setLong(1, sale.bookId());
        ps.setInt(2, sale.quantity());
    });

SimpleJdbcInsert asks the JDBC driver which columns the table has (through DatabaseMetaData, the API from Batch Updates and Metadata) and builds the INSERT from the keys of the map you pass. The chunked batchUpdate returns one int[] per chunk.

Before the lambda form existed, the same job was written with a BatchPreparedStatementSetter, and you will still meet it in older code. It has two methods: setValues fills the placeholders for row number i, and getBatchSize tells Spring how many rows there are:

Java
jdbc.batchUpdate("INSERT INTO sale (book_id, qty) VALUES (?, ?)",
    new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Sale sale = sales.get(i);
            ps.setLong(1, sale.bookId());
            ps.setInt(2, sale.quantity());
        }

        @Override
        public int getBatchSize() {
            return sales.size();
        }
    });

Spring prepares the statement once, calls setValues for each index, adds each to the JDBC batch and executes it, so a thousand rows cost a handful of round trips instead of a thousand. Some performance notes:

  • Chunk big lists (the batchSize argument above, often 500 to 5,000) so one batch does not hold gigabytes of parameters or a lock for minutes.
  • Use one transaction for the whole batch (see below); a commit per row throws the gain away.
  • Some drivers only turn a JDBC batch into a multi-row statement when asked: for MySQL add rewriteBatchedStatements=true to the URL, for PostgreSQL reWriteBatchedInserts=true.
  • The return array shows rows affected per statement; a value of Statement.SUCCESS_NO_INFO (-2) means "succeeded, count unknown", which several drivers return for batches.
  • A failure part-way through throws BatchUpdateException (translated by Spring); inside a transaction it rolls back every row of the batch.

The model shows the mechanisms at work.

Java SimpleJdbcInsert with metadata, keys and chunked batches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The metadata query ran once and found the three insertable columns. The second book had no price in the map, so SimpleJdbcInsert inserted NULL there. That is convenient but also a trap: a typo in a map key ("tilte") is silently ignored, and the column gets NULL (or the insert fails on a NOT NULL column). The 2,500 sales went to the database in three round trips; with the batching options from Batch Updates and Metadata (rewriteBatchedStatements=true for MySQL, reWriteBatchedInserts=true for PostgreSQL) the driver can merge each chunk into a few multi-row inserts.

JdbcClient: the modern fluent API

Spring Framework 6.1 added JdbcClient, a single fluent API that covers both positional and named parameters and maps rows to records automatically. For new code it is usually the nicest choice:

Java
@Repository
public class BookRepository {
    private final JdbcClient jdbc;

    public BookRepository(JdbcClient jdbc) { this.jdbc = jdbc; }

    public List<Book> findCheaperThan(BigDecimal max) {
        return jdbc.sql("SELECT * FROM book WHERE price < :max ORDER BY price")
            .param("max", max)
            .query(Book.class)              // columns -> record components, published_on -> publishedOn
            .list();
    }

    public Optional<Book> findById(long id) {
        return jdbc.sql("SELECT * FROM book WHERE id = ?").param(id).query(Book.class).optional();
    }

    public long count() {
        return jdbc.sql("SELECT COUNT(*) FROM book").query(Long.class).single();
    }

    public long insert(NewBook book) {
        var keys = new GeneratedKeyHolder();
        jdbc.sql("INSERT INTO book (title, published_on, price, in_stock) VALUES (:title, :publishedOn, :price, :inStock)")
            .paramSource(book)              // record components become named parameters
            .update(keys);
        return keys.getKey().longValue();
    }
}

query(Book.class) maps columns to record components or properties, translating snake_case column names to camelCase names. query(Long.class) for a simple type reads a single column. list(), optional(), single() and stream() choose how many results you expect. You can still pass your own RowMapper with query(mapper). The next model implements the core of that API with reflection over record components.

Java A fluent JdbcClient with record mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every query reads like a sentence: SQL, parameters, target type, cardinality. published_on landed in publishedOn and in_stock in the primitive inStock without a hand-written mapper. optional() turned "no row" into Optional.empty, while single() insisted on exactly one row and failed on purpose when three matched. The real JdbcClient adds proper named-parameter parsing (the one from the previous model), IN-list expansion, stream() and params(...) for several positional values at once.

Which API should you choose? In new code, JdbcClient for most queries; JdbcTemplate when you need its lower-level methods (custom PreparedStatementCreator, fetch size, batchUpdate); SimpleJdbcInsert when key retrieval is all you need. They all share the same DataSource, transactions and exceptions, so mixing them is fine.

Transactions with Spring JDBC

@Transactional works with JdbcTemplate and JdbcClient exactly as it does with JPA:

Java
@Service
public class TransferService {
    private final JdbcClient jdbc;

    public TransferService(JdbcClient jdbc) { this.jdbc = jdbc; }

    @Transactional
    public void transfer(long from, long to, BigDecimal amount) {
        jdbc.sql("UPDATE account SET balance = balance - ? WHERE id = ?").params(amount, from).update();
        int credited = jdbc.sql("UPDATE account SET balance = balance + ? WHERE id = ?").params(amount, to).update();
        if (credited == 0) {
            throw new IllegalArgumentException("No account " + to);    // unchecked: rolls back
        }
    }
}

The trick that makes this work is connection binding. When the transactional proxy (Aspect-Oriented Programming) starts a transaction, the transaction manager takes one connection from the pool, turns off autocommit and stores the connection in a ThreadLocal. Every template call on that thread asks DataSourceUtils.getConnection(dataSource), which returns the bound connection instead of a new one. So both updates run on the same connection, inside the same transaction, and the manager commits or rolls back at the end. Without a transaction, each call borrows its own connection in autocommit mode, and each statement commits on its own. The model shows both cases.

Java Thread-bound connections behind Transactional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without a transaction, the two updates used connections #1 and #2, the debit committed immediately, and 100 vanished from the total. Inside a transaction, both statements ran on the single bound connection, so the rollback undid the debit. Two consequences follow from the ThreadLocal. Work you hand to another thread (an @Async method, a parallel stream, a CompletableFuture) does not join the transaction. And the rollback rule is the same as in JPA: unchecked exceptions roll back, checked ones commit unless you say rollbackFor. Entity Lifecycle and Transactions covers propagation and these rules in detail, and JDBC Transactions explains isolation levels.

Calling stored procedures and functions

Some databases keep business logic inside the database: a stored procedure is a named block of SQL code that you call with parameters, and a stored function is the same but returns a value. Banks and ERP systems often use them heavily. JDBC calls them through CallableStatement with the escape syntax {call name(?, ?)}, which brings the usual ceremony: register each OUT parameter with its SQL type, execute, read results, close. Spring offers three levels of help.

Take a MySQL procedure that raises the salary of everyone in a department and reports how many people were affected and the new payroll total:

SQL
CREATE PROCEDURE raise_salary(IN dept_id INT, IN percent DECIMAL(5,2),
                              OUT affected INT, OUT new_total DECIMAL(12,2))
BEGIN
  UPDATE employee SET salary = salary * (1 + percent / 100) WHERE department_id = dept_id;
  SET affected = ROW_COUNT();
  SELECT SUM(salary) INTO new_total FROM employee WHERE department_id = dept_id;
END

SimpleJdbcCall: the easy way

SimpleJdbcCall is the sibling of SimpleJdbcInsert: you give it the procedure name, and it reads the parameter names and types from the database metadata, so you usually declare nothing:

Java
@Repository
public class PayrollDao {

    private final SimpleJdbcCall raiseSalary;

    public PayrollDao(DataSource dataSource) {
        this.raiseSalary = new SimpleJdbcCall(dataSource).withProcedureName("raise_salary");
    }

    public RaiseResult raise(int departmentId, BigDecimal percent) {
        Map<String, Object> out = raiseSalary.execute(
            new MapSqlParameterSource()
                .addValue("dept_id", departmentId)
                .addValue("percent", percent));
        return new RaiseResult((Integer) out.get("affected"), (BigDecimal) out.get("new_total"));
    }
}

execute returns a Map with the OUT parameters under their names. A few details:

  • Metadata lookup costs a round trip the first time, and it depends on the driver. Where it is unreliable (some Oracle packages, overloaded procedures), call .withoutProcedureColumnMetaDataAccess() and declare the parameters yourself with .declareParameters(new SqlParameter("dept_id", Types.INTEGER), new SqlOutParameter("affected", Types.INTEGER)).
  • Functions use .withFunctionName("tax_for") and executeFunction(BigDecimal.class, params) to get the return value directly.
  • Result sets returned by a procedure are collected under names you choose: .returningResultSet("employees", new BeanPropertyRowMapper<>(Employee.class)), and you read out.get("employees") as a List.
  • A schema or catalog can be added with .withSchemaName("hr") and .withCatalogName("payroll_pkg") (Oracle packages use the catalog name).
  • Parameter names are matched ignoring case and underscores in many databases; if a value arrives as null unexpectedly, a name mismatch is the first thing to check.

StoredProcedure: a reusable, typed class

When a procedure is called from many places, wrap it in a subclass of StoredProcedure. You declare the parameters in the constructor (order matters for IN parameters), compile once, and expose a typed method:

Java
public class RaiseSalaryProcedure extends StoredProcedure {

    public RaiseSalaryProcedure(DataSource dataSource) {
        super(dataSource, "raise_salary");
        declareParameter(new SqlParameter("dept_id", Types.INTEGER));
        declareParameter(new SqlParameter("percent", Types.DECIMAL));
        declareParameter(new SqlOutParameter("affected", Types.INTEGER));
        declareParameter(new SqlOutParameter("new_total", Types.DECIMAL));
        compile();                                          // validates the declaration once
    }

    public Map<String, Object> raise(int deptId, BigDecimal percent) {
        return execute(Map.of("dept_id", deptId, "percent", percent));
    }
}

Instances are thread-safe once compiled, so create one as a singleton bean. For the lowest level, JdbcTemplate.call(CallableStatementCreator, List<SqlParameter>) lets you build the CallableStatement yourself, and jdbcTemplate.execute("{call cleanup()}", (CallableStatementCallback<Void>) cs -> { cs.execute(); return null; }) covers one-off calls. Exceptions from all of these are translated to DataAccessException, like the rest of Spring JDBC (see Exception translation above).

A runnable model on H2

Stored procedures with OUT parameters are a feature of MySQL, PostgreSQL (procedures since version 11), SQL Server and Oracle. H2 supports functions written in Java (CREATE ALIAS) and calls them with the same {call ...} syntax, so we can run the idea honestly: below, a Java function lives in the database, and a small SimpleCall class does what SimpleJdbcCall does: it builds the text from the declared parameters, binds named values, executes, and returns the result as a map.

Java A SimpleJdbcCall-style helper calling a database function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The map has one entry named by returning(...), just like the Map that SimpleJdbcCall.execute returns for a function result, and a missing input is reported by name before the database is even called.

Should you use stored procedures?

Procedures run close to the data, can reduce round trips for multi-step operations, and let a DBA control access to tables. Against that: they live outside your version control unless you manage them with Flyway migrations, they are written in a vendor-specific language, they are harder to unit test, and logic ends up split between two places. Use them when an existing system already depends on them or when a batch operation truly benefits from running inside the database. For new application logic, keep the rules in Java and use plain SQL, as described in the next section.

Spring JDBC, JPA or something else?

  • Spring JDBC fits reporting queries, bulk updates, stored procedures (Statements, Stored Procedures and ResultSet Types), and teams that want to see every SQL statement. You write more SQL, but nothing happens behind your back.
  • JPA with Spring Data fits rich domain models with relationships, where change tracking and derived queries save a lot of code. Its costs are covered in Fetching Strategies and Performance.
  • Spring Data JDBC is a middle ground: repositories and aggregates like Spring Data JPA, but no lazy loading or persistence context.
  • jOOQ generates Java classes from your schema so that SQL itself is type-checked.

Mixing is common and safe: a JPA application can inject a JdbcClient for one complex report, and both share the same transaction when they use the same DataSource and the JPA transaction manager.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You need to load each author together with a list of their books from a single JOIN query. Which callback fits best?

    A RowMapper turns exactly one row into one object. Grouping several rows into one parent object needs the whole result set, which a ResultSetExtractor receives.
  2. 2. jdbc.queryForObject("SELECT title FROM book WHERE id = ?", String.class, 99) finds no row. What happens?

    queryForObject expects exactly one row. Zero rows throw EmptyResultDataAccessException and several rows throw IncorrectResultSizeDataAccessException; use query(...) or JdbcClient's optional() when a missing row is normal.
  3. 3. With NamedParameterJdbcTemplate, what SQL is prepared for WHERE id IN (:ids) when ids is List.of(4, 8, 15)?

    Spring expands a collection parameter into one placeholder per element and binds each value, so the values never become part of the SQL text.
  4. 4. Why does catching DataIntegrityViolationException also catch a duplicate-key error?

    Spring translates SQLExceptions into a hierarchy. DuplicateKeyException extends DataIntegrityViolationException, which covers all constraint violations.
  5. 5. Inside a @Transactional method, two JdbcTemplate.update calls run. Why do they share one transaction?

    The transaction manager stores the connection in a ThreadLocal; DataSourceUtils.getConnection returns it to every template call on that thread. Work on other threads doesn't take part.

Summary

  • Spring JDBC removes JDBC's ceremony (connections, statements, loops, closing, checked exceptions) while you keep writing the SQL.
  • Spring Boot auto-configures a pooled DataSource, JdbcTemplate, NamedParameterJdbcTemplate, JdbcClient and a transaction manager; schema.sql and data.sql run for embedded databases (or with spring.sql.init.mode=always).
  • JdbcTemplate offers query, queryForObject, update and batchUpdate, with three callbacks: RowMapper (row to object), ResultSetExtractor (whole result to one object) and RowCallbackHandler (streaming).
  • NamedParameterJdbcTemplate rewrites :name to ? and expands collections for IN lists. SimpleJdbcInsert builds inserts from table metadata and returns generated keys.
  • JdbcClient (Spring 6.1+) is the modern fluent API: sql(...).param(...).query(Book.class).list(), with automatic record mapping and optional()/single().
  • Every SQLException becomes an unchecked, portable DataAccessException subclass, such as DuplicateKeyException or EmptyResultDataAccessException.
  • @Transactional works by binding one connection to the current thread; template calls on that thread join the transaction automatically.

Next: Spring MVC