JPA Part 1 — JDBC Foundation
JDBC fundamentals, Spring JdbcTemplate, connection pooling with HikariCP
- Understand the JDBC driver and connection lifecycle
- Use JdbcTemplate to execute queries without boilerplate
- Configure HikariCP connection pooling properties
Database Connectivity Architecture Plain JDBC Spring Boot JDBC Template Connection Pooling
JdbcTemplate solves them. Understanding this sequence makes JPA and Hibernate make much more sense.Table of Contents
- The Complete Database Connectivity Architecture
- What Is JDBC?
- What Is an ORM Framework?
- Database Drivers — The JDBC Implementations
- Plain JDBC — Without Spring Boot
- Problems with Plain JDBC
- Spring Boot JDBC — JdbcTemplate
- How JdbcTemplate Solves Each Plain JDBC Problem
- Connection Pooling — Hikari CP
- JdbcTemplate — Complete Method Reference
- Full Working Example — Spring Boot JDBC
- Summary & Quick Reference
- Interview Notes
- Practice Questions
1. The Complete Database Connectivity Architecture
Before writing a single line of database code, you must understand the full stack of components involved when a Spring Boot application talks to a database. Each layer has a specific role.
1┌─────────────────────────────────────────┐2│ Your Spring Boot Application │3│ (Application Logic / Beans) │4└─────────────────┬───────────────────────┘5 │ interacts with6 ▼7┌─────────────────────────────────────────┐8│ JPA (Interface) │9│ Java Persistence API — defines APIs │10│ Does NOT provide implementation │11└─────────────────┬───────────────────────┘12 │ implemented by13 ▼14┌─────────────────────────────────────────┐15│ ORM Framework (e.g. Hibernate) │16│ Provides JPA implementation │17│ Maps Java objects ↔ DB tables │18└─────────────────┬───────────────────────┘19 │ uses20 ▼21┌─────────────────────────────────────────┐22│ JDBC API (Interface) │23│ Java Database Connectivity │24│ Defines: getConnection, query, etc. │25│ Does NOT provide implementation │26└─────────────────┬───────────────────────┘27 │ implemented by28 ▼29┌─────────────────────────────────────────┐30│ Specific DB Driver (Impl) │31│ MySQL → Connector/J │32│ PostgreSQL → PostgreSQL JDBC Driver │33│ H2 → H2 Database Engine │34└─────────────────┬───────────────────────┘35 │ connects to36 ▼37┌─────────────────────────────────────────┐38│ Database Server │39│ MySQL / PostgreSQL / H2 / etc. │40└─────────────────────────────────────────┘The Key Principle Interfaces All the Way Down
This architecture is built on interfaces:
| Layer | Type | Who Implements It |
|---|---|---|
| JPA | Interface | Hibernate, EclipseLink, OpenJPA |
| JDBC | Interface | Database-specific drivers |
| Drivers | Implementation | MySQL, PostgreSQL, H2 vendors |
Why This Layering Matters
Because your application talks to interfaces, not implementations:
- You can switch from MySQL to PostgreSQL without changing your application code.
- You can switch from Hibernate to EclipseLink without rewriting your queries.
- Each layer is independently replaceable.
Architecture Diagram
2. What Is JDBC?
Definition
JDBC (Java Database Connectivity) is a Java API (a collection of interfaces) that provides a standard way to:
- Connect to a relational database
- Execute SQL queries (SELECT, INSERT, UPDATE, DELETE, CREATE)
- Process the results returned from the database
What JDBC Is NOT
JDBC does not actually perform these operations. It only defines the contract (the interfaces). The actual implementation of "how to connect to MySQL" is in the MySQL JDBC driver, not in JDBC itself.
Real-World Analogy
JDBC is like a universal power socket standard. The standard defines the shape and voltage requirements, but the actual electricity flows through a specific power grid (the driver). You plug in the same way regardless of which city you're in — only the underground wiring (driver implementation) differs.
3. What Is an ORM Framework?
Definition
ORM (Object-Relational Mapping) is a technique (and framework) that acts as a bridge between Java objects and relational database tables.
Without ORM:
- You write SQL strings manually:
INSERT INTO users (name, age) VALUES (?, ?) - You manually map result set columns back to Java objects
With ORM (JPA + Hibernate):
- You create Java classes (entities) annotated with
@Entity - ORM generates SQL automatically
- ORM maps result rows back to Java objects automatically
ORM vs JDBC Comparison
| Feature | Plain JDBC | ORM (JPA + Hibernate) |
|---|---|---|
| SQL queries | Write manually | Auto-generated for common operations |
| Result mapping | Manual (column by column) | Automatic (via entity annotations) |
| Code verbosity | High | Low |
| Control over SQL | Full | Partial (can still use native queries) |
| Learning curve | Low | Higher |
| Performance tuning | Easier | Requires understanding of ORM behavior |
4. Database Drivers The JDBC Implementations
Each relational database has its own driver — a library that implements the JDBC API and knows how to communicate with that specific database.
| Database | Driver Name | Class to Load |
|---|---|---|
| MySQL | Connector/J | com.mysql.cj.jdbc.Driver |
| PostgreSQL | PostgreSQL JDBC Driver | org.postgresql.Driver |
| H2 | H2 Database Engine | org.h2.Driver |
| Oracle | Oracle JDBC Driver | oracle.jdbc.driver.OracleDriver |
| SQL Server | Microsoft JDBC Driver | com.microsoft.sqlserver.jdbc.SQLServerDriver |
Why the Driver Class Needs to Be "Loaded"
Before using a driver, it must be loaded into the JVM. This registers the driver with the DriverManager so that when you call DriverManager.getConnection(url), the DriverManager knows which driver to use for the given URL.
1// Manually loading a driver (plain JDBC)2Class.forName("org.h2.Driver"); // Loads H2 driver into JVMIn Spring Boot, this is done automatically at application startup — you never write Class.forName(...) yourself.
Key Insight Code Doesn't Change When You Switch Databases
1// Your code always calls the same JDBC API methods2Connection conn = DriverManager.getConnection(url, username, password);3PreparedStatement ps = conn.prepareStatement("SELECT * FROM users");4ResultSet rs = ps.executeQuery();Whether url points to MySQL, PostgreSQL, or H2, your code is identical. Only the driver class and URL format change — and in Spring Boot, even those just change in application.properties.
5. Plain JDBC Without Spring Boot
To understand why Spring Boot's JdbcTemplate is valuable, you must first see what you would write without it.
Setting Up H2 (In-Memory Database)
H2 is a lightweight, in-memory relational database perfect for development and testing:
- In-memory mode: Data exists only while the application runs. On shutdown, data is lost.
- File mode: Data persists to disk even after shutdown.
We use in-memory mode here: jdbc:h2:mem:userdb
Class 1 `DatabaseConnection` (Connection Management)
1public class DatabaseConnection {2
3 public Connection getConnection() throws SQLException, ClassNotFoundException {4
5 // Step 1: Load the driver into the JVM6 Class.forName("org.h2.Driver");7
8 // Step 2: Establish a connection with the database9 // Format: jdbc:<db-type>:<mode>:<db-name>10 // If the DB doesn't exist, H2 creates it automatically11 Connection connection = DriverManager.getConnection(12 "jdbc:h2:mem:userdb", // URL: H2 in-memory database named "userdb"13 "sa", // Username: default H2 admin (System Administrator)14 "" // Password: empty by default15 );16
17 return connection;18 }19}◆ Line-by-Line Explanation
| Line | Explanation |
|---|---|
Class.forName("org.h2.Driver") | Loads the H2 JDBC driver into JVM memory and registers it with DriverManager |
DriverManager.getConnection(url, user, pass) | Asks DriverManager to create a new database connection using the registered driver |
"jdbc:h2:mem:userdb" | JDBC URL: protocol=jdbc, DB type=h2, mode=mem (in-memory), DB name=userdb |
"sa" | Default H2 username (SA = System Administrator) |
"" | Default H2 password (empty string) |
Class 2 `UserDao` (Data Access Object)
1public class UserDao {2
3 // Method 1: Create the users table4 public void createTable() throws SQLException, ClassNotFoundException {5 DatabaseConnection dbConn = new DatabaseConnection();6 Connection connection = dbConn.getConnection(); // Get fresh connection7 Statement statement = null;8
9 try {10 String sql = "CREATE TABLE users (" +11 "user_id INT AUTO_INCREMENT PRIMARY KEY, " +12 "username VARCHAR(255), " +13 "age INT)";14
15 statement = connection.createStatement();16 statement.executeUpdate(sql); // Execute DDL (CREATE TABLE)17
18 } catch (SQLException e) {19 e.printStackTrace();20 } finally {21 // Must close all resources to prevent memory leaks22 if (statement != null) statement.close();23 if (connection != null) connection.close();24 }25 }26
27 // Method 2: Insert a new user28 public void createUser(String username, int age) throws SQLException, ClassNotFoundException {29 DatabaseConnection dbConn = new DatabaseConnection();30 Connection connection = dbConn.getConnection();31 PreparedStatement preparedStatement = null;32
33 try {34 // ? = placeholder for dynamic values (prevents SQL injection)35 String sql = "INSERT INTO users (username, age) VALUES (?, ?)";36
37 preparedStatement = connection.prepareStatement(sql);38 preparedStatement.setString(1, username); // Index 1 = first ?39 preparedStatement.setInt(2, age); // Index 2 = second ?40
41 preparedStatement.executeUpdate(); // Execute INSERT42
43 } catch (SQLException e) {44 e.printStackTrace();45 } finally {46 if (preparedStatement != null) preparedStatement.close();47 if (connection != null) connection.close();48 }49 }50
51 // Method 3: Read all users52 public String readUsers() throws SQLException, ClassNotFoundException {53 DatabaseConnection dbConn = new DatabaseConnection();54 Connection connection = dbConn.getConnection();55 PreparedStatement preparedStatement = null;56 ResultSet resultSet = null;57 StringBuilder result = new StringBuilder();58
59 try {60 String sql = "SELECT * FROM users";61 preparedStatement = connection.prepareStatement(sql);62 resultSet = preparedStatement.executeQuery(); // Returns ResultSet63
64 // ResultSet = a cursor over the result rows65 while (resultSet.next()) {66 result.append("ID: ").append(resultSet.getInt("user_id"))67 .append(", Name: ").append(resultSet.getString("username"))68 .append(", Age: ").append(resultSet.getInt("age"))69 .append("\n");70 }71
72 } catch (SQLException e) {73 e.printStackTrace();74 } finally {75 // Close ALL resources in reverse order of creation76 if (resultSet != null) resultSet.close();77 if (preparedStatement != null) preparedStatement.close();78 if (connection != null) connection.close();79 }80
81 return result.toString();82 }83}◆ Key Concepts in Plain JDBC
Statement vs PreparedStatement:
| Type | Use When | SQL Injection Safe? |
|---|---|---|
Statement | No dynamic values (DDL like CREATE TABLE) | N/A |
PreparedStatement | Dynamic values (INSERT, SELECT with WHERE) | ✅ Yes — ? placeholders are parameterized |
executeUpdate() vs executeQuery():
| Method | Used For | Returns |
|---|---|---|
executeUpdate() | INSERT, UPDATE, DELETE, CREATE TABLE | int (rows affected) |
executeQuery() | SELECT | ResultSet (result rows) |
ResultSet:
- A cursor that starts before the first row.
- Call
resultSet.next()to move to the next row — returnsfalsewhen no more rows. - Use typed getters:
getInt("column"),getString("column"),getDouble("column").
Step-by-Step Execution Flow (Plain JDBC)
6. Problems with Plain JDBC
Plain JDBC works, but it forces developers to write a large amount of repetitive, error-prone boilerplate code. Here are the five main problems:
Problem 1 Manual Driver Class Loading
1// Must be done every time, in every class that needs a connection2Class.forName("org.h2.Driver");- You must know the exact driver class name for your database.
- If you forget it or misspell it, you get a
ClassNotFoundExceptionat runtime. - Every developer on the team must remember to do this.
Problem 2 Manual Database Connection Creation
1Connection connection = DriverManager.getConnection(url, username, password);- You must manually obtain a connection before every query.
- The URL, username, and password are hardcoded or must be managed separately.
- No centralized connection configuration.
Problem 3 Vague Exception Handling (`SQLException`)
1} catch (SQLException e) {2 e.printStackTrace(); // What went wrong? No idea.3}SQLException is an extremely broad, generic exception. It can represent dozens of different failure types:
- Primary key violation
- Duplicate key (unique constraint)
- Foreign key violation
- Query timeout
- Connection failure
- Syntax error in SQL
With plain JDBC, you cannot easily distinguish between these without parsing error codes manually. This makes error handling messy, unreliable, and hard to maintain.
Problem 4 Manual Resource Closing (Risk of Memory Leaks)
1} finally {2 if (resultSet != null) resultSet.close();3 if (preparedStatement != null) preparedStatement.close();4 if (connection != null) connection.close();5}- Every method must have a
finallyblock closing every resource in the right order. - If you forget to close even one resource, you get a resource leak — connections stay open indefinitely.
- At scale, leaked connections exhaust the database's connection limit, causing failures.
- This
finallyblock must be duplicated in every single DAO method.
Problem 5 No Connection Pooling
1// Creates a brand-new connection every single time2Connection connection = DriverManager.getConnection(url, username, password);Creating a database connection is expensive — it involves:
- Network handshake
- Authentication
- Session initialization
For a high-traffic application handling thousands of requests per second, creating a new connection for every request would be catastrophically slow.
Connection pooling solves this by pre-creating a set of connections, reusing them across requests, and returning them to the pool after use. With plain JDBC, you must implement this yourself — a non-trivial engineering effort.
Summary of Plain JDBC Problems
7. Spring Boot JDBC JdbcTemplate
What Is `JdbcTemplate`?
JdbcTemplate is a Spring class that wraps JDBC and removes all the boilerplate code. It handles:
- Driver loading
- Connection creation and management
- Exception translation (vague → specific)
- Resource closing (connections, statements, result sets)
- Connection pooling (via
DataSource)
You focus entirely on your SQL query and result mapping. Spring handles everything else.
Step 1 Add Dependencies (`pom.xml`)
1<!-- Spring Boot JDBC support (includes JdbcTemplate) -->2<dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-jdbc</artifactId>5</dependency>6
7<!-- H2 in-memory database (replace with MySQL/Postgres dependency if needed) -->8<dependency>9 <groupId>com.h2database</groupId>10 <artifactId>h2</artifactId>11 <scope>runtime</scope>12</dependency>xml
mysql
mysql-connector-java
runtime
`
Your JdbcTemplate code does not change — only application.properties` needs to be updated.Step 2 Configure `application.properties`
1# Database URL2spring.datasource.url=jdbc:h2:mem:userdb3
4# JDBC Driver class (Spring Boot often auto-detects this)5spring.datasource.driver-class-name=org.h2.Driver6
7# Database credentials8spring.datasource.username=sa9spring.datasource.password=10
11# Connection pool settings (Hikari — Spring Boot's default)12spring.datasource.hikari.maximum-pool-size=1013spring.datasource.hikari.minimum-idle=5properties
spring.datasource.url=jdbc:mysql://localhost:3306/userdb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=yourpassword
``
Everything else in your Java code stays the same.Step 3 Create the Entity (Plain Java Object)
1public class User {2
3 private Long userId;4 private String username;5 private int age;6
7 // Constructors8 public User() {}9 public User(Long userId, String username, int age) {10 this.userId = userId;11 this.username = username;12 this.age = age;13 }14
15 // Getters and Setters16 public Long getUserId() { return userId; }17 public void setUserId(Long userId) { this.userId = userId; }18
19 public String getUsername() { return username; }20 public void setUsername(String username) { this.username = username; }21
22 public int getAge() { return age; }23 public void setAge(int age) { this.age = age; }24
25 @Override26 public String toString() {27 return "User{userId=" + userId + ", username='" + username + "', age=" + age + "}";28 }29}Step 4 Create the Repository Class
1@Repository2public class UserRepository {3
4 @Autowired5 private JdbcTemplate jdbcTemplate;6 // Spring auto-creates JdbcTemplate bean using the DataSource configured7 // in application.properties — no manual setup needed8
9 // Create the users table10 public void createTable() {11 String sql = "CREATE TABLE IF NOT EXISTS users (" +12 "user_id INT AUTO_INCREMENT PRIMARY KEY, " +13 "username VARCHAR(255), " +14 "age INT)";15 jdbcTemplate.execute(sql); // For DDL statements (no dynamic values)16 }17
18 // Insert a new user19 public void insertUser(String username, int age) {20 String sql = "INSERT INTO users (username, age) VALUES (?, ?)";21 jdbcTemplate.update(sql, username, age);22 // No try-catch, no finally, no connection management — JdbcTemplate handles it all23 }24
25 // Read all users26 public List<User> getUsers() {27 String sql = "SELECT * FROM users";28 return jdbcTemplate.query(sql, (rs, rowNum) -> {29 User user = new User();30 user.setUserId(rs.getLong("user_id"));31 user.setUsername(rs.getString("username"));32 user.setAge(rs.getInt("age"));33 return user;34 });35 }36}◆ What `@Repository` Does
@Repository is a specialization of @Component. It does two things:
- Marks the class for component scanning — Spring creates a bean automatically.
- Enables Spring's exception translation — any
SQLExceptionthrown inside a@Repositoryclass is automatically converted to a specific SpringDataAccessExceptionsubclass (e.g.,DuplicateKeyException,QueryTimeoutException).
Step 5 Create the Service Class
1@Service2public class UserService {3
4 @Autowired5 private UserRepository userRepository;6
7 public void initializeTable() {8 userRepository.createTable();9 }10
11 public void addUser(String username, int age) {12 // Business logic can go here before/after DB operation13 userRepository.insertUser(username, age);14 }15
16 public List<User> getAllUsers() {17 List<User> users = userRepository.getUsers();18 // Business logic on the fetched data can go here19 users.forEach(System.out::println);20 return users;21 }22}Step 6 Controller
1@RestController2public class UserController {3
4 @Autowired5 private UserService userService;6
7 @GetMapping("/api/jdbc/users")8 public List<User> getUsers() {9 userService.initializeTable();10 userService.addUser("Alice", 30);11 userService.addUser("Bob", 25);12 return userService.getAllUsers();13 }14}Console Output:
1User{userId=1, username='Alice', age=30}2User{userId=2, username='Bob', age=25}HTTP Response:
1[2 { "userId": 1, "username": "Alice", "age": 30 },3 { "userId": 2, "username": "Bob", "age": 25 }4]8. How JdbcTemplate Solves Each Plain JDBC Problem
Problem 1 Solved Driver Loading is Automatic
At application startup, Spring Boot reads spring.datasource.driver-class-name from application.properties and calls Class.forName(...) automatically — in the DriverManager class, before your code runs.
1Application starts2 → Spring reads application.properties3 → Spring calls Class.forName("org.h2.Driver") internally4 → Driver registered with DriverManager5 → You never write Class.forName() anywhereProblem 2 Solved Connection Management via `DataSource`
Spring Boot creates a DataSource bean based on your application.properties. JdbcTemplate uses this DataSource to get connections automatically whenever you call execute(), update(), or query().
Internally, when you call jdbcTemplate.update(sql, ...), Spring calls DataSourceUtils.getConnection(dataSource) — you never call DriverManager.getConnection() yourself.
Problem 3 Solved Granular Exception Translation
Plain JDBC throws the generic SQLException. Spring Boot translates these into specific, meaningful exceptions:
| Spring Exception | Meaning |
|---|---|
DuplicateKeyException | Unique constraint / primary key violation |
DataIntegrityViolationException | Foreign key, NOT NULL, check constraint violation |
QueryTimeoutException | Query took too long |
EmptyResultDataAccessException | Expected one row, got zero |
CannotAcquireLockException | Database lock contention |
DataAccessException | Parent of all Spring DB exceptions |
These are all in the org.springframework.dao package. You can catch exactly the exception type you care about:
1try {2 userRepository.insertUser("Alice", 30);3} catch (DuplicateKeyException e) {4 // Handle duplicate user specifically5 return ResponseEntity.status(409).body("User already exists");6} catch (DataAccessException e) {7 // Handle any other DB error8 return ResponseEntity.status(500).body("Database error");9}Problem 4 Solved Automatic Resource Closing
JdbcTemplate closes all resources in its finally block internally. You never write:
1// ❌ Never need this in Spring Boot JDBC2if (resultSet != null) resultSet.close();3if (preparedStatement != null) preparedStatement.close();4if (connection != null) connection.close();Internally, JdbcTemplate does something like:
1// JdbcTemplate internal cleanup (simplified)2} finally {3 JdbcUtils.closeResultSet(rs);4 JdbcUtils.closeStatement(stmt);5 DataSourceUtils.releaseConnection(con, dataSource);6 // Note: "release" means return to pool, not necessarily close7}Problem 5 Solved Built-In Connection Pooling (Hikari CP)
Spring Boot automatically configures HikariCP as the default connection pool. When you set up application.properties, Spring Boot wires everything — you get a production-grade connection pool with zero extra configuration.
Default Hikari settings:
- Maximum pool size: 10 connections
- Minimum idle connections: 10
- Both configurable in
application.properties
Before vs After Comparison
1Plain JDBC (one method): Spring Boot JdbcTemplate (same method):2────────────────────────────────────── ──────────────────────────────────────3Class.forName("org.h2.Driver"); // Nothing here — auto at startup4Connection conn = DriverManager // Nothing here — JdbcTemplate manages5 .getConnection(url, user, pass);6try {7 PreparedStatement ps = String sql = "INSERT INTO users8 conn.prepareStatement( (username, age) VALUES (?, ?)";9 "INSERT INTO users jdbcTemplate.update(sql, username, age);10 (username, age) VALUES (?, ?)");11 ps.setString(1, username); // Done. That's the entire method.12 ps.setInt(2, age);13 ps.executeUpdate();14} catch (SQLException e) {15 e.printStackTrace();16} finally {17 if (ps != null) ps.close();18 if (conn != null) conn.close();19}9. Connection Pooling Hikari CP
What Is a Connection Pool?
A connection pool is a cache of pre-created, ready-to-use database connections. Instead of creating a new connection for every request (expensive), the pool lends an existing connection and takes it back when done.
Why Connections Are Expensive to Create
Creating a DB connection involves:
- TCP/IP network handshake
- Database authentication (username/password validation)
- Session state initialization on the DB server
- Memory allocation on both client and server
For a web application serving hundreds of requests per second, creating a new connection per request would add 50-200ms of latency just for the connection — before any query runs.
Hikari CP Spring Boot's Default
HikariCP is the fastest, most efficient JDBC connection pool available. Spring Boot uses it by default.
1# Hikari pool configuration in application.properties2spring.datasource.hikari.maximum-pool-size=10 # Max connections in pool3spring.datasource.hikari.minimum-idle=5 # Min idle connections maintained4spring.datasource.hikari.connection-timeout=30000 # Max wait for connection (ms)5spring.datasource.hikari.idle-timeout=600000 # Max idle time before removal (ms)DataSource bean in your AppConfig class.Custom DataSource Bean (Override Default)
1@Configuration2public class AppConfig {3
4 @Bean5 public DataSource dataSource() {6 HikariDataSource dataSource = new HikariDataSource();7 dataSource.setDriverClassName("org.h2.Driver");8 dataSource.setJdbcUrl("jdbc:h2:mem:userdb");9 dataSource.setUsername("sa");10 dataSource.setPassword("");11 dataSource.setMaximumPoolSize(20); // Custom pool size12 dataSource.setMinimumIdle(5);13 return dataSource;14 }15}When you define a DataSource bean this way, application.properties datasource settings are ignored — your bean takes full control.
10. JdbcTemplate Complete Method Reference
JdbcTemplate provides several methods for different types of SQL operations. Here is a complete guide to the most commonly used ones.
`execute()` DDL Statements
Use for: CREATE TABLE, DROP TABLE, ALTER TABLE — statements with no dynamic values and no result.
1String sql = "CREATE TABLE IF NOT EXISTS users " +2 "(user_id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), age INT)";3jdbcTemplate.execute(sql);`update()` INSERT, UPDATE, DELETE
Two flavors:
◆ Flavor 1 With Varargs (Simple)
Use for: Simple INSERT/UPDATE/DELETE with a small number of parameters.
1// INSERT2String insertSql = "INSERT INTO users (username, age) VALUES (?, ?)";3jdbcTemplate.update(insertSql, "Alice", 30); // varargs: values replace ? in order4
5// UPDATE6String updateSql = "UPDATE users SET age = ? WHERE username = ?";7jdbcTemplate.update(updateSql, 31, "Alice");8
9// DELETE10String deleteSql = "DELETE FROM users WHERE user_id = ?";11jdbcTemplate.update(deleteSql, 1L);◆ Flavor 2 With `PreparedStatementSetter` (Complex)
Use for: Complex queries where you need precise control over parameter binding.
PreparedStatementSetter is a functional interface — use a lambda expression.
1String sql = "INSERT INTO users (username, age) VALUES (?, ?)";2
3jdbcTemplate.update(sql, (PreparedStatement ps) -> {4 ps.setString(1, "Alice"); // ? index 1 = username5 ps.setInt(2, 30); // ? index 2 = age6});PreparedStatementSetter) when you need to set NULL values, use setNull(), or handle complex type conversions.`query()` SELECT Multiple Rows
Use for: Fetching multiple rows and mapping each row to a Java object.
RowMapper is a functional interface — use a lambda expression. It is called once per row in the result set.
1String sql = "SELECT * FROM users";2
3List<User> users = jdbcTemplate.query(sql, (ResultSet rs, int rowNum) -> {4 // This lambda is called once per row5 User user = new User();6 user.setUserId(rs.getLong("user_id"));7 user.setUsername(rs.getString("username"));8 user.setAge(rs.getInt("age"));9 return user; // Return the mapped object for this row10});11// Returns List<User> with one User per rowInternal execution of query():
`queryForList()` SELECT Single Column, Multiple Rows
Use for: Fetching one specific column's values across multiple rows.
1// Get all usernames2String sql = "SELECT username FROM users";3List<String> usernames = jdbcTemplate.queryForList(sql, String.class);4// Returns: ["Alice", "Bob", "Charlie", ...]5
6// Get all user IDs7String idSql = "SELECT user_id FROM users";8List<Long> ids = jdbcTemplate.queryForList(idSql, Long.class);`queryForObject()` SELECT Single Row Single Object
Use for: Fetching exactly one row and mapping it to a Java object.
queryForObject throws EmptyResultDataAccessException.
If the query returns more than one row, it throws IncorrectResultSizeDataAccessException.
Use only when you are confident the query returns exactly one row.1String sql = "SELECT * FROM users WHERE user_id = ?";2
3User user = jdbcTemplate.queryForObject(4 sql,5 new Object[]{1L}, // Dynamic parameter: user_id = 16 (rs, rowNum) -> {7 User u = new User();8 u.setUserId(rs.getLong("user_id"));9 u.setUsername(rs.getString("username"));10 u.setAge(rs.getInt("age"));11 return u;12 }13);`queryForObject()` SELECT Single Value
Use for: Fetching a single scalar value (a count, a sum, a single field).
1// Count total users2String countSql = "SELECT COUNT(*) FROM users";3Integer count = jdbcTemplate.queryForObject(countSql, Integer.class);4System.out.println("Total users: " + count);5
6// Get one user's age7String ageSql = "SELECT age FROM users WHERE username = ?";8Integer age = jdbcTemplate.queryForObject(ageSql, Integer.class, "Alice");Method Summary Table
| Method | SQL Type | Returns | Use When |
|---|---|---|---|
execute(sql) | DDL (CREATE, ALTER, DROP) | void | No result, no dynamic values |
update(sql, args...) | INSERT, UPDATE, DELETE | int (rows affected) | Simple modifications |
update(sql, pss) | INSERT, UPDATE, DELETE | int (rows affected) | Complex parameter binding |
query(sql, rowMapper) | SELECT | List | Multiple rows → objects |
queryForList(sql, type) | SELECT one column | List | One column, multiple rows |
queryForObject(sql, args, rowMapper) | SELECT | T (single object) | Exactly one row → object |
queryForObject(sql, type, args...) | SELECT | T (single value) | Exactly one scalar value |
11. Full Working Example Spring Boot JDBC
Here is the complete, runnable Spring Boot JDBC application:
Project Structure
1src/2├── main/3│ ├── java/com/example/4│ │ ├── controller/UserController.java5│ │ ├── service/UserService.java6│ │ ├── repository/UserRepository.java7│ │ └── model/User.java8│ └── resources/9│ └── application.properties10└── pom.xml`User.java`
1package com.example.model;2
3public class User {4 private Long userId;5 private String username;6 private int age;7
8 public User() {}9
10 public User(Long userId, String username, int age) {11 this.userId = userId;12 this.username = username;13 this.age = age;14 }15
16 public Long getUserId() { return userId; }17 public void setUserId(Long userId) { this.userId = userId; }18 public String getUsername() { return username; }19 public void setUsername(String username) { this.username = username; }20 public int getAge() { return age; }21 public void setAge(int age) { this.age = age; }22
23 @Override24 public String toString() {25 return "User{userId=" + userId + ", username='" + username + "', age=" + age + "}";26 }27}`UserRepository.java`
1package com.example.repository;2
3import com.example.model.User;4import org.springframework.beans.factory.annotation.Autowired;5import org.springframework.jdbc.core.JdbcTemplate;6import org.springframework.stereotype.Repository;7import java.util.List;8
9@Repository10public class UserRepository {11
12 @Autowired13 private JdbcTemplate jdbcTemplate;14
15 public void createTable() {16 jdbcTemplate.execute(17 "CREATE TABLE IF NOT EXISTS users (" +18 "user_id INT AUTO_INCREMENT PRIMARY KEY, " +19 "username VARCHAR(255), " +20 "age INT)"21 );22 }23
24 public void insertUser(String username, int age) {25 jdbcTemplate.update(26 "INSERT INTO users (username, age) VALUES (?, ?)",27 username, age28 );29 }30
31 public List<User> getUsers() {32 return jdbcTemplate.query(33 "SELECT * FROM users",34 (rs, rowNum) -> {35 User user = new User();36 user.setUserId(rs.getLong("user_id"));37 user.setUsername(rs.getString("username"));38 user.setAge(rs.getInt("age"));39 return user;40 }41 );42 }43
44 public int getUserCount() {45 return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM users", Integer.class);46 }47
48 public List<String> getAllUsernames() {49 return jdbcTemplate.queryForList("SELECT username FROM users", String.class);50 }51
52 public User getUserById(Long id) {53 return jdbcTemplate.queryForObject(54 "SELECT * FROM users WHERE user_id = ?",55 new Object[]{id},56 (rs, rowNum) -> {57 User user = new User();58 user.setUserId(rs.getLong("user_id"));59 user.setUsername(rs.getString("username"));60 user.setAge(rs.getInt("age"));61 return user;62 }63 );64 }65}`UserService.java`
1package com.example.service;2
3import com.example.model.User;4import com.example.repository.UserRepository;5import org.springframework.beans.factory.annotation.Autowired;6import org.springframework.stereotype.Service;7import java.util.List;8
9@Service10public class UserService {11
12 @Autowired13 private UserRepository userRepository;14
15 public void initializeTable() {16 userRepository.createTable();17 }18
19 public void addUser(String username, int age) {20 userRepository.insertUser(username, age);21 }22
23 public List<User> getAllUsers() {24 return userRepository.getUsers();25 }26}`UserController.java`
1package com.example.controller;2
3import com.example.model.User;4import com.example.service.UserService;5import org.springframework.beans.factory.annotation.Autowired;6import org.springframework.web.bind.annotation.GetMapping;7import org.springframework.web.bind.annotation.RestController;8import java.util.List;9
10@RestController11public class UserController {12
13 @Autowired14 private UserService userService;15
16 @GetMapping("/api/jdbc/users")17 public List<User> getUsers() {18 userService.initializeTable();19 userService.addUser("Alice", 30);20 userService.addUser("Bob", 25);21 return userService.getAllUsers();22 }23}`application.properties`
1spring.datasource.url=jdbc:h2:mem:userdb2spring.datasource.driver-class-name=org.h2.Driver3spring.datasource.username=sa4spring.datasource.password=5
6spring.datasource.hikari.maximum-pool-size=107spring.datasource.hikari.minimum-idle=512. Summary & Quick Reference
Architecture Recap
Plain JDBC vs Spring Boot JDBC
| Concern | Plain JDBC | Spring Boot JdbcTemplate |
|---|---|---|
| Driver loading | Class.forName(...) manually | Automatic at startup |
| Connection creation | DriverManager.getConnection(...) | Automatic via DataSource |
| Exception clarity | Generic SQLException | Specific: DuplicateKeyException, etc. |
| Resource closing | Manual finally block | Automatic inside JdbcTemplate |
| Connection pooling | Manual implementation | HikariCP auto-configured |
| Code lines per operation | ~15-25 lines | 1-3 lines |
Key Bullets
- JPA is an interface; Hibernate is its most popular implementation.
- JDBC is an interface; DB drivers (MySQL, H2, Postgres) are its implementations.
- ORM maps Java objects ↔ relational database tables; eliminates manual SQL for basic CRUD.
- H2 is an in-memory relational database — data is lost on application shutdown (useful for dev/testing).
JdbcTemplateremoves all boilerplate: noClass.forName, no manual connections, nofinallyblocks.@Repositoryenables exception translation —SQLException→ specificDataAccessExceptionsubtypes.- HikariCP is Spring Boot's default connection pool — pre-creates connections, reuses them, dramatically improves performance.
- Switching databases = change
application.propertiesonly. Java code stays the same. update()for INSERT/UPDATE/DELETE;query()for multiple rows;queryForObject()for single row or single value;queryForList()for single column.
13. Interview Notes
Q1: What is the difference between JDBC and JPA?
- JDBC is a low-level API for connecting to and querying relational databases using SQL. JPA is a higher-level ORM specification that maps Java objects to DB tables, auto-generates SQL, and eliminates most manual query writing. JDBC is the foundation that JPA/Hibernate sits on top of.
Q2: What is Hibernate's relationship to JPA?
- Hibernate is the most popular implementation of the JPA specification. JPA defines the interfaces and rules; Hibernate provides the actual implementation. Other JPA implementations include EclipseLink and OpenJPA.
Q3: What problems does JdbcTemplate solve over plain JDBC?
- Automatic driver loading, automatic connection management, granular exception translation (from
SQLExceptionto specific subtypes), automatic resource closing, and built-in connection pooling viaDataSource.
Q4: What is a connection pool and why is it important?
- A connection pool is a cache of pre-created DB connections. Creating a connection is expensive (network + authentication). A pool pre-creates connections, lends them out for requests, and recycles them — dramatically reducing per-request latency and improving throughput.
Q5: What is the default connection pool in Spring Boot?
- HikariCP (
HikariDataSource). Default maximum pool size is 10. Configurable viaspring.datasource.hikari.*properties.
Q6: What is the difference between execute(), update(), and query() in JdbcTemplate?
execute()is for DDL (CREATE, DROP, ALTER — no results, no dynamic params).update()is for DML that modifies data (INSERT, UPDATE, DELETE — returns rows affected).query()is for SELECT operations that return multiple rows mapped to objects viaRowMapper.
Q7: What is RowMapper and why is it a functional interface?
RowMapperis an interface with one method:T mapRow(ResultSet rs, int rowNum). It is called once per row in a SELECT result, mapping columns to a Java object. Being a functional interface means you can implement it with a lambda expression.
Q8: What happens if queryForObject() finds no rows?
- It throws
EmptyResultDataAccessException. If it finds more than one row, it throwsIncorrectResultSizeDataAccessException. Use it only when you are certain the query returns exactly one row.
Q9: What is @Repository and how does it differ from @Component?
@Repositoryis a specialization of@Component— it still creates a bean. The additional feature is exception translation: Spring wraps the class in a proxy that catchesSQLExceptionand translates it into specificDataAccessExceptionsubclasses.
Q10: How do you switch from H2 to MySQL in a Spring Boot JDBC application?
- Change
application.properties: updatespring.datasource.urlto the MySQL JDBC URL, changedriver-class-nametocom.mysql.cj.jdbc.Driver, set actual username/password. Also replace the H2 Maven dependency with the MySQL connector dependency. Zero Java code changes needed.
14. Practice Questions
Easy
- Name the four layers in the Spring Boot database connectivity hierarchy.
- What is the difference between
execute()andupdate()inJdbcTemplate? - What does
Class.forName("org.h2.Driver")do in plain JDBC? - What is the default connection pool used by Spring Boot?
- What annotation marks a class as a Spring data access component with exception translation?
Medium
- Write a complete
UserRepositorymethod usingJdbcTemplatethat fetches a single user by ID. Handle the case where the user might not exist. - Explain the five problems with plain JDBC and state exactly which
JdbcTemplatemechanism resolves each one. - What is the difference between
queryForList()andquery()inJdbcTemplate? When would you use each? - How would you configure a custom Hikari connection pool with a maximum of 20 connections without using
application.properties? - What is the difference between
executeUpdate()andexecuteQuery()at the plain JDBC level?
Hard
- Trace the full execution path — from your code calling
jdbcTemplate.update(sql, "Alice", 30)all the way to a row being inserted in the database — naming every Spring class and method involved. - Design a complete Spring Boot JDBC application that: creates a
productstable, inserts 5 products, retrieves products by category usingquery(), gets a count of all products usingqueryForObject(), and deletes a product by ID. - If you are running 1000 concurrent HTTP requests, each needing a DB connection, and your Hikari pool has a maximum of 10 connections, what happens to the other 990 requests? What Spring Boot property controls how long a request waits before timing out?
- What are the risks of using
queryForObject()in production code where the underlying data could be deleted concurrently? How would you handle this safely? - Compare using
JdbcTemplatewithPreparedStatementSettervs varargsupdate(). In what specific scenarios doesPreparedStatementSetterprovide an advantage?
@Entity, @Id, @Column, repository interfaces, and how Hibernate auto-generates SQL — building directly on the JDBC foundation established here.Mastery check
How well can you recall this?
Finished this lesson?