From DAO classes to JdbcClient and JdbcTemplate repositories
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite DAO method from Section 13 needed ten lines of plumbing around one line of SQL, and every method repeated it. Saving a product or finding an order should read as one short statement.
What JdbcTemplate removes: connections, try-with-resources, SQLException
JdbcTemplate is Spring's classic JDBC helper. You give it the SQL, the parameter values and a way to read a row; it borrows a connection, runs the statement and closes everything.
Compare this Section 13 DAO method with what Spring does for you. Most of its lines are plumbing; only the SQL and the new Product(...) are about the shop.
public Product save(NewProduct p) { String sql = "INSERT INTO products (sku, name, category_id, price, stock) VALUES (?, ?, ?, ?, ?)"; return db.run("add product " + p.sku(), c -> { try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, p.sku()); // ...and 4 more set calls ps.executeUpdate(); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); return new Product(keys.getInt(1), p.sku(), p.name(), p.categoryId(), p.price(), p.stock(), true); } } });}Example 1 · TemplateProductRepository.java: reads with JdbcTemplate
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;
/** The same reads with the older JdbcTemplate API. */@Repositoryclass TemplateProductRepository {
private static final String SELECT = "SELECT product_id, sku, name, price, stock FROM products";
private final JdbcTemplate jdbcTemplate; private final ProductRowMapper mapper = new ProductRowMapper();
TemplateProductRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; }
List<ProductRow> findByCategory(long categoryId) { return jdbcTemplate.query(SELECT + " WHERE category_id = ? ORDER BY product_id", mapper, categoryId); }
/** Exactly one row expected: zero rows throws EmptyResultDataAccessException. */ ProductRow findById(long id) { return jdbcTemplate.queryForObject(SELECT + " WHERE product_id = ?", mapper, id); }
int countActive() { return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM products WHERE is_active = TRUE", Integer.class); }}-- JdbcTemplate: books (category 5) ProductRow[id=9, sku=BK-CLEAN, name=Clean Code, price=499.00, stock=30] ProductRow[id=10, sku=BK-PRAG, name=The Pragmatic Programmer, price=650.00, stock=22] ProductRow[id=11, sku=BK-ATOMIC, name=Atomic Habits, price=399.00, stock=50] Active products: 14 JdbcTemplate 99: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
What this code does
- Each method is one line of real work: the SQL, the mapper and the parameter. No connection, no
close(), noSQLExceptionanywhere. queryForObjectexpects exactly one row. For id 99 it throwsEmptyResultDataAccessException, so "not found" needs a try/catch: one reasonJdbcClient.optional()is nicer.
Every DAO method repeated the same plumbing: get a connection, prepare, set parameters one by one, run, open the generated keys, close two resources and wrap the checked SQLException. Each repeat was a chance to forget a close(). Spring writes that fixed part and you write the changing part, an idea called the template pattern.
With Spring the plumbing is gone, and so is SQLException. Spring translates it into DataAccessException, an unchecked exception with clear subclasses such as DuplicateKeyException. You catch what you can handle and let the rest reach the global error handler.
JdbcClient: sql(), param(), query(), list(), optional() and update()
JdbcClient is Spring's fluent API for SQL: you write the SQL, bind the values and say how a row becomes an object. Spring does the connection, the statement and the cleanup.
One chain reads in order: sql(...) sets the statement, param(...) binds a value, query(...) says how to read rows, and list(), optional() or single() says how many rows you expect.
Example 2 · ClientProductRepository.java: the same with JdbcClient
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;import java.util.Optional;
import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.jdbc.support.GeneratedKeyHolder;import org.springframework.jdbc.support.KeyHolder;import org.springframework.stereotype.Repository;
/** Products with JdbcClient: one fluent chain per query. */@Repositoryclass ClientProductRepository {
private static final String SELECT = "SELECT product_id, sku, name, price, stock FROM products";
private final JdbcClient jdbc; private final ProductRowMapper mapper = new ProductRowMapper();
ClientProductRepository(JdbcClient jdbc) { this.jdbc = jdbc; }
List<ProductRow> findByCategory(long categoryId) { return jdbc.sql(SELECT + " WHERE category_id = ? ORDER BY product_id") .param(categoryId) .query(mapper) .list(); }
Optional<ProductRow> findById(long id) { return jdbc.sql(SELECT + " WHERE product_id = :id") .param("id", id) .query(mapper) .optional(); }
long insert(String sku, String name, long categoryId, BigDecimal price, int stock) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbc.sql("INSERT INTO products (sku, name, category_id, price, stock) VALUES (?, ?, ?, ?, ?)") .params(sku, name, categoryId, price, stock) .update(keyHolder); return keyHolder.getKey().longValue(); }
/** Returns how many rows changed: 0 means no product has this id. */ int updatePrice(long id, BigDecimal price) { return jdbc.sql("UPDATE products SET price = ? WHERE product_id = ?") .params(price, id) .update(); }}-- JdbcClient: books (category 5) ProductRow[id=9, sku=BK-CLEAN, name=Clean Code, price=499.00, stock=30] ProductRow[id=10, sku=BK-PRAG, name=The Pragmatic Programmer, price=650.00, stock=22] ProductRow[id=11, sku=BK-ATOMIC, name=Atomic Habits, price=399.00, stock=50] JdbcClient 9: Optional[ProductRow[id=9, sku=BK-CLEAN, name=Clean Code, price=499.00, stock=30]] JdbcClient 99: Optional.empty
What this code does
- One chain per query:
sql→param→query(mapper)→list()oroptional().findByIduses a named parameter:id;findByCategoryuses a positional?. - A missing id gives
Optional.empty, not an exception, so the service can writefindById(id).orElseThrow(() -> notFound(id)).
Spring Boot creates a JdbcClient bean (Spring Framework 6.1 and later), so a repository asks for it in its constructor. Parameters are positional (? with param(value)) or named (:id with param("id", value)). Never paste a value into the SQL text with +: a parameter is sent separately and can never change the statement.
The ending decides what comes back, and update() handles writes:
query(mapper).list(): every row, as aList; maybe none.query(mapper).optional(): zero or one row, as anOptional; empty means "not found".query(Long.class).single(): exactly one value of a one-column result; it throws otherwise.update(): INSERT, UPDATE or DELETE; returns the rows changed.
Predict the output
What does the chain return?
Product 99 and category 42 do not exist. Pick the result.
Round 1 of 3
What is found?
A RowMapper that builds Product records
A RowMapper<T> turns the current row of a ResultSet into one T. Spring moves the cursor and calls mapRow once per row; you only read the columns by name.
The mapper holds the same rs.getLong(...) code as in Section 13, now written once per repository and reused by every query.
public ProductRow mapRow(ResultSet rs, int rowNum) throws SQLException { return new ProductRow( rs.getLong("product_id"), rs.getString("sku"), rs.getString("name"), rs.getBigDecimal("price"), rs.getInt("stock"));}Example 3 · src/main/java/com/shoplite/category/JdbcCategoryRepository.java
Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database
package com.shoplite.category;
import java.sql.ResultSet;import java.sql.SQLException;import java.util.Collection;import java.util.List;import java.util.Optional;
import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.jdbc.support.GeneratedKeyHolder;import org.springframework.jdbc.support.KeyHolder;import org.springframework.stereotype.Repository;
/** Categories in the MySQL table categories (category_id, name, parent_id). */@Repositoryclass JdbcCategoryRepository implements CategoryRepository {
private static final String SELECT = "SELECT category_id, name, parent_id FROM categories";
private final JdbcClient jdbc;
JdbcCategoryRepository(JdbcClient jdbc) { this.jdbc = jdbc; }
@Override public List<Category> findAll() { return jdbc.sql(SELECT + " ORDER BY category_id") .query(this::mapRow) .list(); }
@Override public Optional<Category> findById(Long id) { return jdbc.sql(SELECT + " WHERE category_id = ?") .param(id) .query(this::mapRow) .optional(); }
@Override public List<Category> findAllById(Collection<Long> ids) { if (ids.isEmpty()) { return List.of(); // "IN ()" is not valid SQL } return jdbc.sql(SELECT + " WHERE category_id IN (:ids) ORDER BY category_id") .param("ids", ids) .query(this::mapRow) .list(); }
@Override public Optional<Category> findByNameIgnoreCase(String name) { return jdbc.sql(SELECT + " WHERE name = ?") .param(name) .query(this::mapRow) .optional(); }
@Override public boolean existsById(Long id) { return exists("SELECT EXISTS (SELECT 1 FROM categories WHERE category_id = ?)", id); }
@Override public boolean existsByParentId(Long parentId) { return exists("SELECT EXISTS (SELECT 1 FROM categories WHERE parent_id = ?)", parentId); }
@Override public boolean hasProducts(Long id) { return exists("SELECT EXISTS (SELECT 1 FROM products WHERE category_id = ?)", id); }
@Override public Category insert(Category category) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbc.sql("INSERT INTO categories (name, parent_id) VALUES (?, ?)") .params(category.getName(), category.getParentId()) .update(keyHolder); long id = keyHolder.getKey().longValue(); // the AUTO_INCREMENT value MySQL generated return new Category(id, category.getName(), category.getParentId()); }
@Override public boolean update(Category category) { int rows = jdbc.sql("UPDATE categories SET name = ?, parent_id = ? WHERE category_id = ?") .params(category.getName(), category.getParentId(), category.getId()) .update(); return rows == 1; }
@Override public boolean deleteById(Long id) { return jdbc.sql("DELETE FROM categories WHERE category_id = ?").param(id).update() == 1; }
private boolean exists(String sql, Long id) { return jdbc.sql(sql).param(id).query(Boolean.class).single(); }
private Category mapRow(ResultSet rs, int rowNum) throws SQLException { return new Category( rs.getLong("category_id"), rs.getString("name"), rs.getObject("parent_id", Long.class)); // getLong would turn NULL into 0 }}$ curl -i http://localhost:8080/api/v1/categories
HTTP/1.1 200
Content-Type: application/json
Content-Length: 299
Date: Fri, 16 Oct 2026 06:46:15 GMT
[{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Mobiles","parentId":1},{"id":3,"name":"Laptops","parentId":1},{"id":4,"name":"Accessories","parentId":1},{"id":5,"name":"Books","parentId":null},{"id":6,"name":"Fashion","parentId":null},{"id":7,"name":"Home & Kitchen","parentId":null}]What this code does
mapRowis a private method used asthis::mapRow.getObject("parent_id", Long.class)keepsnullfor top-level categories, which the JSON shows as"parentId":null.findAllByIduses a named list parameter,IN (:ids); Spring expands it toIN (?, ?, ?). An empty list returns early becauseIN ()is not valid SQL.EXISTSqueries read one boolean withquery(Boolean.class).single(), and the write methods return whether exactly one row changed.
The same mapper works with both APIs: jdbcTemplate.query(sql, mapper, args) and jdbc.sql(sql).query(mapper). ShopLite writes it as a private method and passes this::mapRow, which keeps the column names next to the SQL that selects them.
Watch out for nullable columns. rs.getLong("parent_id") returns 0 for SQL NULL, and a top-level category would wrongly get parent 0; rs.getObject("parent_id", Long.class) returns null. Money stays exact with rs.getBigDecimal("price").
Inserting and reading the generated id with a KeyHolder
A KeyHolder collects the keys the database generated during an INSERT, such as an AUTO_INCREMENT id. Pass a GeneratedKeyHolder to update(keyHolder).
After the INSERT, read the new id with keyHolder.getKey().longValue(). The repository returns the saved row with that id.
Example 4 · RepositoryDemo.java: insert, update and the exceptions
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.dao.DataAccessException;import org.springframework.dao.DuplicateKeyException;import org.springframework.dao.EmptyResultDataAccessException;import org.springframework.stereotype.Component;
/** java -jar jdbc-lab.jar repo */@Componentclass RepositoryDemo implements ApplicationRunner {
private final ClientProductRepository client; private final TemplateProductRepository template;
RepositoryDemo(ClientProductRepository client, TemplateProductRepository template) { this.client = client; this.template = template; }
@Override public void run(ApplicationArguments args) { if (!args.getNonOptionArgs().contains("repo")) { return; } System.out.println("-- JdbcClient: books (category 5)"); client.findByCategory(5).forEach(System.out::println); System.out.println("-- JdbcTemplate: books (category 5)"); template.findByCategory(5).forEach(System.out::println); System.out.println("Active products: " + template.countActive());
System.out.println("-- findById"); System.out.println("JdbcClient 9: " + client.findById(9)); System.out.println("JdbcClient 99: " + client.findById(99)); try { template.findById(99); } catch (EmptyResultDataAccessException e) { System.out.println("JdbcTemplate 99: " + e.getClass().getSimpleName() + ": " + e.getMessage()); }
System.out.println("-- insert and update"); long id = client.insert("ACC-KB100", "Zebronics Wireless Keyboard", 4, new BigDecimal("999.00"), 30); System.out.println("New product id: " + id); System.out.println("Rows updated for " + id + ": " + client.updatePrice(id, new BigDecimal("949.00"))); System.out.println("Rows updated for 999: " + client.updatePrice(999, new BigDecimal("949.00")));
System.out.println("-- errors"); try { client.insert("ACC-KB100", "Another keyboard", 4, new BigDecimal("499.00"), 5); } catch (DuplicateKeyException e) { System.out.println(e.getClass().getSimpleName() + " is a DataAccessException: " + (e instanceof DataAccessException)); System.out.println("Cause: " + e.getMostSpecificCause().getMessage()); } try { client.insert("ACC-KB200", "Mouse", 42, new BigDecimal("499.00"), 5); } catch (DataAccessException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMostSpecificCause().getMessage()); } }}-- insert and update New product id: 16 Rows updated for 16: 1 Rows updated for 999: 0 -- errors DuplicateKeyException is a DataAccessException: true Cause: Duplicate entry 'ACC-KB100' for key 'products.uq_products_sku' DataIntegrityViolationException: Cannot add or update a child row: a foreign key constraint fails (`shoplite`.`products`, CONSTRAINT `fk_products_category` FOREIGN KEY (`category_id`) REFERENCES `categories` (`category_id`))
What this code does
- The KeyHolder returns 16, the next AUTO_INCREMENT value. Updating id 16 changes 1 row; updating id 999 changes 0, with no exception.
- The second
ACC-KB100breaksuq_products_sku, and Spring throwsDuplicateKeyException, a subclass ofDataAccessException. Category 42 breaks a foreign key and becomesDataIntegrityViolationException. - These messages name tables and constraints: fine in a log, never in an API response.
This is how POST /api/v1/products can answer 201 Created with "id": 16 and a Location header: the repository returns the saved row with its new id, and the controller builds the URL from it.
MySQL hands back the key as a BigInteger, so use getKey().longValue(); getKeyAs(Long.class) fails here because the value is not a Long object. For a plain UPDATE or DELETE, the returned row count is what matters: 1 means done, 0 means no row had that id.
DataAccessException, DuplicateKeyException to 409, and 0 rows updated to 404
DataAccessException is the root of Spring's database exceptions. Spring reads MySQL's error code and throws a clear unchecked subclass, such as DuplicateKeyException.
A broken UNIQUE constraint becomes DuplicateKeyException, a foreign key that points nowhere becomes DataIntegrityViolationException, and a lost connection becomes CannotGetJdbcConnectionException.
Example 5 · ProductService and the handler: 0 rows to 404, duplicates to 409
Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database
// src/main/java/com/shoplite/product/ProductService.java (parts)@Transactionalpublic void delete(Long id) { if (repository.isOrdered(id)) { throw new ResourceInUseException("Product " + id + " appears in orders and cannot be deleted. Set isActive to false instead."); } if (!repository.deleteById(id)) { throw notFound(id); } log.info("Deleted product {}", id);}
private void save(Product product) { if (!repository.update(product)) { throw notFound(product.getId()); // 0 rows updated -> 404 (deleted by someone else after load()) }}
// src/main/java/com/shoplite/common/GlobalExceptionHandler.java (part)/** Two requests raced past the service's check; the UNIQUE constraint caught the second one. */@ExceptionHandler(DuplicateKeyException.class)ProblemDetail handleDuplicateKey(DuplicateKeyException ex, HttpServletRequest request) { log.warn("Duplicate key on {} {}: {}", request.getMethod(), request.getRequestURI(), ex.getMostSpecificCause().getMessage()); return problem(HttpStatus.CONFLICT, "already-exists", "Resource already exists", "A resource with the same unique value already exists.", request.getRequestURI());}$ curl -i -X DELETE http://localhost:8080/api/v1/products/1
HTTP/1.1 409
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:46:04 GMT
{"type":"https://shoplite.example/problems/in-use","title":"Resource in use","status":409,"detail":"Product 1 appears in orders and cannot be deleted. Set isActive to false instead.","instance":"/api/v1/products/1"}
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 204
Date: Fri, 16 Oct 2026 06:46:05 GMT
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:46:05 GMT
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Product 16 was not found.","instance":"/api/v1/products/16"}What this code does
- Product 1 was ordered before, so the service refuses with 409
in-usebefore it even tries the DELETE. - Product 16 is deleted (204). The second DELETE changes 0 rows,
deleteByIdreturnsfalse, and the service throws the 404. - If two POSTs with the same SKU pass
checkSkuIsFreeat the same moment, the UNIQUE constraint rejects the second one andhandleDuplicateKeystill answers 409, with a safe detail.
All are unchecked, so repository methods stay free of throws and try. ShopLite maps them to the API contract in two places. The service checks first and throws a clear error (A product with SKU MOB-RN13 already exists., 409); two requests can still race past that check, and then MySQL's UNIQUE constraint stops the second one, so the global handler turns DuplicateKeyException into the same 409 without leaking SQL or constraint names.
A row count of 0 is not an exception at all. UPDATE ... WHERE product_id = 99 simply changes nothing, so the repository returns false, and the service turns that into ResourceNotFoundException, which the handler sends as 404.
Find the bug
Find the faulty line
Click the line that breaks the rules of this lesson.
This handler leaks database details to the client. Which line?
Round 1 of 2DataAccessException message to the client. It contains table and constraint names, and sometimes the SQL. Log it on the server; send the contract's safe detail.Next step
Check your understanding
12 quick questions