🎯 What you will learn
JDBC (Java Database Connectivity) is the standard API for talking to any relational database from Java. Spring's JdbcTemplate wraps raw JDBC and eliminates boilerplate: you write SQL, Spring handles connections, statements, and result sets. By the end of this lesson you will understand:
- How
JdbcTemplateis auto-configured by Spring Boot fromapplication.properties queryForList,queryForMap, andqueryForObject— which to use and when- Parameterised queries with
?placeholders to prevent SQL injection - JOIN queries and aggregate
GROUP BYqueries jdbc.update()for INSERT, UPDATE, and DELETE statements- Switching the datasource from H2 (dev) to PostgreSQL (production) with zero code changes
? placeholders matter.
🧾 Real-world scenario
Arjun's team needs to produce a daily balance report from the accounts table. Rather than adding ORM overhead for a read-only reporting job, he uses Spring's JdbcTemplate — clean SQL, typed results, zero boilerplate connection management.
🗄️ JdbcTemplate setup + queryForList
Spring Boot auto-configures JdbcTemplate when spring-boot-starter-jdbc is on the classpath and a datasource is defined in application.properties. Inject it into any Spring bean via the constructor and you are ready to query.
Key insight: Each row in the result is a Map<String, Object> where the key is the column name (uppercase in H2) and the value is the Java type that JDBC maps the SQL type to. No custom class required — perfect for reporting endpoints.
🔗 Parameterised query + JOIN
queryForMap returns exactly one row as a Map. Pass parameters as additional arguments after the SQL string — Spring binds them via PreparedStatement, which prevents SQL injection. Use jdbc.update() for DML statements.
SQL injection safety: Never concatenate user input into SQL strings like "WHERE account_no = '" + accountNo + "'". The ? placeholder tells JDBC to treat the value as data, not as SQL syntax — a malicious input like ' OR '1'='1 is safely bound as a literal string.
📊 Aggregate query — GROUP BY
JdbcTemplate handles any SQL that your database supports — including GROUP BY, HAVING, window functions, and CTEs. This makes it ideal for analytical reporting where hand-tuned SQL outperforms ORM-generated queries.
📋 JdbcTemplate method reference
| Method | Use when | Returns |
|---|---|---|
queryForList(sql, args...) | Multiple rows, no custom class needed | List<Map<String,Object>> |
queryForMap(sql, args...) | Exactly one row; throws if 0 or 2+ found | Map<String,Object> |
queryForObject(sql, type, args...) | Single column, single row (e.g. COUNT) | T |
query(sql, rowMapper, args...) | Multiple rows mapped to a custom class | List<T> |
update(sql, args...) | INSERT, UPDATE, DELETE | int (rows affected) |
execute(sql) | DDL — CREATE TABLE, DROP TABLE | void |
🎤 Interview Q&A
queryForList returns multiple rows as List<Map>. queryForMap returns exactly one row as Map (throws if 0 or 2+ rows found). queryForObject returns exactly one row mapped to a type via RowMapper (e.g., String.class for a single column).
Spring Boot auto-configures HikariCP (the fastest connection pool) when spring-boot-starter-jdbc or spring-boot-starter-data-jpa is on the classpath. JdbcTemplate borrows a connection from the pool per query and returns it automatically.
A RowMapper<T> converts each ResultSet row to a T instance. Implement RowMapper<Account> and pass it to jdbc.query(sql, rowMapper, params). Since Java 8 you can use a lambda: (rs, row) -> new Account(rs.getLong("id"), ...).
A variant of JdbcTemplate that uses named parameters (:accountNo) instead of positional ? placeholders. Useful when a query has many parameters or when the same value appears multiple times: ":fromDate AND :toDate". Pass a Map<String,Object> or SqlParameterSource.
Choose JDBC for: (1) complex analytical queries with GROUP BY, window functions, or CTEs that are awkward in JPQL; (2) batch inserts/updates where JPA's per-entity lifecycle overhead is too slow; (3) read-only reporting jobs with hand-tuned SQL; (4) when the data model doesn't map cleanly to ORM entities (e.g., aggregation tables, event log tables). JPA shines for transactional CRUD on well-defined domain entities.
📝 Quiz — 5 questions
JdbcTemplate.queryForList() return?queryForMap() finds no row?Next: Spring Data JPA Basics — zero-SQL CRUD →
⚠️ Common mistakes
"WHERE id = " + id. Always use ? placeholders. JdbcTemplate will bind them safely via PreparedStatement.query() with a RowMapper and check if the list is empty.query() with a RowMapper or queryForList().✅ Key takeaways
- JdbcTemplate eliminates raw JDBC boilerplate while keeping full SQL control
- Always use
?placeholders — never concatenate user input into SQL strings - queryForList → multiple rows; queryForMap → exactly one row; update → DML
- Spring Boot auto-configures HikariCP connection pool from application.properties
- Switch datasource from H2 to PostgreSQL/MySQL by changing 3 properties — no code changes
From raw SQL to full ORM in one arc
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →