🎯 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 JdbcTemplate is auto-configured by Spring Boot from application.properties
  • queryForList, queryForMap, and queryForObject — which to use and when
  • Parameterised queries with ? placeholders to prevent SQL injection
  • JOIN queries and aggregate GROUP BY queries
  • jdbc.update() for INSERT, UPDATE, and DELETE statements
  • Switching the datasource from H2 (dev) to PostgreSQL (production) with zero code changes
💼 Interview reality: "What does JdbcTemplate do for you over raw JDBC?" and "How do you prevent SQL injection with JDBC?" are asked in every Java backend interview. Know the boilerplate JdbcTemplate eliminates and why ? placeholders matter.

🧾 Real-world scenario

🏦
Real-world scenario · SouthBank India (Mumbai)
Direct SQL queries on the accounts ledger

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.

curl -s http://localhost:8766/api/jdbc/accounts
JdbcDemoController.javaLesson 27 · queryForList — all accounts
verified output
[ { "ID": 1, "ACCOUNT_NO": "SB-100001", "HOLDER_NAME": "Arjun Sharma", "BALANCE": 85000.0, "ACCOUNT_TYPE": "SAVINGS" }, { "ID": 2, "ACCOUNT_NO": "SB-100002", "HOLDER_NAME": "Priya Mehta", "BALANCE": 210000.0, "ACCOUNT_TYPE": "CURRENT" }, { "ID": 3, "ACCOUNT_NO": "SB-100003", "HOLDER_NAME": "Vikram Singh", "BALANCE": 47500.0, "ACCOUNT_TYPE": "SAVINGS" }, { "ID": 4, "ACCOUNT_NO": "SB-100004", "HOLDER_NAME": "Deepa Nair", "BALANCE": 125000.0, "ACCOUNT_TYPE": "SAVINGS" } ]

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.

curl -s "http://localhost:8766/api/jdbc/accounts/SB-100001"
JdbcDemoController.javaLesson 27 · queryForMap + JOIN + jdbc.update()
verified output
{ "ID": 1, "ACCOUNT_NO": "SB-100001", "HOLDER_NAME": "Arjun Sharma", "BALANCE": 85000.0, "BRANCH_CITY": "Mumbai" }

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.

curl -s http://localhost:8766/api/jdbc/summary
JdbcDemoController.javaLesson 27 · GROUP BY summary + application.properties config
verified output
[ { "ACCOUNT_TYPE": "SAVINGS", "ACCOUNTS": 3, "TOTAL_BALANCE": 257500.0 }, { "ACCOUNT_TYPE": "CURRENT", "ACCOUNTS": 1, "TOTAL_BALANCE": 210000.0 } ]

📋 JdbcTemplate method reference

MethodUse whenReturns
queryForList(sql, args...)Multiple rows, no custom class neededList<Map<String,Object>>
queryForMap(sql, args...)Exactly one row; throws if 0 or 2+ foundMap<String,Object>
queryForObject(sql, type, args...)Single column, single row (e.g. COUNT)T
query(sql, rowMapper, args...)Multiple rows mapped to a custom classList<T>
update(sql, args...)INSERT, UPDATE, DELETEint (rows affected)
execute(sql)DDL — CREATE TABLE, DROP TABLEvoid

🎤 Interview Q&A

EasyWhat is the difference between queryForList, queryForMap, and queryForObject?
+

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).

EasyHow does JdbcTemplate handle connection pooling?
+

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.

MediumHow do you map a query result to a custom Java class?
+

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"), ...).

MediumWhat is NamedParameterJdbcTemplate?
+

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.

HardWhen would you choose JDBC over JPA/Hibernate?
+

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

Question 1 of 5
What does JdbcTemplate.queryForList() return?
Question 2 of 5
How do you pass a parameter safely to a JdbcTemplate query?
Question 3 of 5
What method do you use for INSERT/UPDATE/DELETE?
Question 4 of 5
What exception is thrown when queryForMap() finds no row?
Question 5 of 5
What is the advantage of JdbcTemplate over raw JDBC?
0
/ 5
Quiz complete!

Next: Spring Data JPA Basics — zero-SQL CRUD →

⚠️ Common mistakes

SQL injection via string concatenation
Never build queries like "WHERE id = " + id. Always use ? placeholders. JdbcTemplate will bind them safely via PreparedStatement.
Ignoring EmptyResultDataAccessException on queryForMap
When queryForMap finds no row it throws, not returns null. Wrap in try/catch or use query() with a RowMapper and check if the list is empty.
Not closing ResultSet in raw JDBC
If you bypass JdbcTemplate and use raw JDBC, you must close Connection, Statement, and ResultSet in a finally block. JdbcTemplate handles this for you.
Using queryForObject for a List
queryForObject expects exactly one row. For multiple rows use 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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →