Skip to content
Visual explainer 3h to learn 3 steps

JDBC & connection pools

Understand what JPA does under the hood.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 14 of 29

In short

JDBC is Java's low-level API for talking to databases, and JPA uses it underneath. A connection pool keeps open connections ready, because opening a new one per request is slow.

Explained simply

JDBC (Java Database Connectivity) is the standard Java API for talking to a database. Every higher tool, from Spring's JdbcTemplate to Hibernate, ends up calling JDBC. Knowing it helps you understand what those tools do for you, and debug them when they go wrong.

The basic flow is simple: get a connection, send a SQL statement, read the rows that come back, and close everything. A driver, a jar provided by the database vendor, turns these calls into the database's network protocol.

Safety matters here. If you glue user input straight into SQL text, an attacker can type SQL instead of a name and run it. PreparedStatement sends the SQL and the values separately, so input is always treated as data. This one habit blocks SQL injection.

Opening a database connection is slow, often tens of milliseconds, because of the network handshake and login. A connection pool such as HikariCP keeps a few connections open and lends them out. Spring Boot sets HikariCP up for you automatically.

Press Play on a diagram to walk through it one step at a time.

LayersWhat sits under JPA
  1. 1
    Spring Data repository

    Your interface, e.g. UserRepository

  2. 2
    JPA / Hibernate

    Maps objects to rows and generates SQL

  3. 3
    HikariCP pool

    Hands out reusable open connections

  4. 4
    JDBC driver

    Speaks the database's network protocol

  5. 5
    Database

    PostgreSQL, MySQL and others

SequenceOne query through a pool
App
HikariCP
Database
  1. 1getConnection()
    App to HikariCP: getConnection()
  2. 2already-open connection
    HikariCP to App: already-open connection
  3. 3PreparedStatement with ? params
    App to Database: PreparedStatement with ? params
  4. 4ResultSet rows
    Database to App: ResultSet rows
  5. 5close() returns it to pool
    App to HikariCP: close() returns it to pool
CycleLife of a pooled connection
  1. 1
    Idle in pool

    Open, logged in, waiting

  2. 2
    Borrowed

    getConnection() hands it to a thread

  3. 3
    In use

    Statements and transactions run

  4. 4
    Returned

    close() gives it back, state is reset

  5. 5
    Retired

    Replaced after maxLifetime or a failure

  6. Back to step 1

In depth

Connections, statements and result sets

A JDBC URL tells the driver where to connect, for example jdbc:postgresql://localhost:5432/shop. Since JDBC 4 the driver registers itself when its jar is on the classpath, so the old Class.forName(...) line is not needed. In applications, get connections from a DataSource (usually a pool) rather than DriverManager, which opens a new physical connection every time.

executeQuery returns a ResultSet for SELECT; executeUpdate returns the number of changed rows for INSERT, UPDATE and DELETE. A ResultSet is a cursor: call next() to move to each row. Column positions start at 1, not 0. Watch out for NULLs: rs.getLong("age") returns 0 for a NULL value. Use rs.getObject("age", Long.class), which returns null, or check rs.wasNull() after reading.

  • Parameter and column indexes start at 1
  • getInt and getLong return 0 for SQL NULL
  • Close ResultSet, Statement and Connection with try-with-resources

SQL injection and its limits

Concatenating input into SQL lets the input change the meaning of the query. With "... WHERE email = '" + email + "'", the input ' OR '1'='1 returns every user. With a PreparedStatement, the SQL text with ? placeholders is sent first and the values are sent separately, so the database never parses the value as SQL.

Placeholders only work for values. You cannot use ? for a table name, a column name or the ASC/DESC keyword. When a user chooses the sort column, check it against a fixed list of allowed names (an allowlist) and only then put it into the SQL text. For a variable number of values in an IN list, PostgreSQL lets you pass one array: WHERE id = ANY(?) with conn.createArrayOf("bigint", ids).

CompareString concatenation vs PreparedStatement
Concatenated SQL
  • Input becomes part of the SQL text
  • ' OR '1'='1 changes the query
  • Quotes in names break it
  • Never do this with user input
PreparedStatement
  • SQL text has ? placeholders
  • Values sent separately as data
  • Types handled by setString, setLong
  • Works for values, not identifiers

Transactions in plain JDBC

A new connection is in auto-commit mode: every statement is its own transaction and is saved at once. To make several statements succeed or fail together, call conn.setAutoCommit(false), run them, and call conn.commit(). If anything throws, call conn.rollback() so nothing is saved. Pooled connections are reset when returned, but restoring auto-commit yourself is still good practice.

This is exactly what Spring's @Transactional does for you behind a proxy: it borrows a connection, turns off auto-commit, runs your method, then commits or rolls back. You can also set the isolation level with setTransactionIsolation, for example TRANSACTION_REPEATABLE_READ, although PostgreSQL's default READ COMMITTED is right for most work.

FlowA JDBC transaction
  1. 1
    Borrow connection

    dataSource.getConnection()

  2. 2
    setAutoCommit(false)

    Start grouping statements

  3. 3
    Run statements

    Debit one account, credit another

  4. 4
    commit()

    Both changes become visible together

  5. 5
    On error: rollback()

    Neither change is saved

Batching and streaming large results

Inserting 10,000 rows one executeUpdate at a time means 10,000 network round trips. With batching, call ps.addBatch() for each row and ps.executeBatch() every few hundred or thousand rows, inside one transaction. For PostgreSQL, adding reWriteBatchedInserts=true to the JDBC URL lets the driver merge them into multi-row INSERTs for a further speed-up.

Reading works the other way. By default the PostgreSQL driver loads the entire result into memory, which can crash the app on a huge table. To stream it in chunks, turn off auto-commit and call ps.setFetchSize(1000); the driver then uses a cursor and fetches 1,000 rows at a time. MySQL's driver has different rules, so check your driver's docs.

  • executeBatch() returns an int[] of update counts
  • Commit batches inside a transaction for speed
  • setFetchSize only streams in PostgreSQL when auto-commit is off

Configuring HikariCP

HikariCP is the default pool in Spring Boot. Its key setting is maximumPoolSize, which defaults to 10. Bigger is not better: a database with 8 CPU cores can only do so much at once, and extra connections just queue inside the database and add overhead. HikariCP's own guide suggests starting near (cores times 2) plus the number of disks and measuring from there. Remember that the total is pool size times app instances: 6 instances with 20 connections need 120 database connections, more than PostgreSQL's default max_connections of 100.

Other settings: connectionTimeout (default 30 seconds) is how long a request waits for a free connection before failing; maxLifetime (default 30 minutes) retires connections before the network or database closes them; leakDetectionThreshold logs a stack trace when a connection is held too long, which finds code that forgets to close.

  • spring.datasource.hikari.maximum-pool-size=10
  • spring.datasource.hikari.connection-timeout=30000
  • spring.datasource.hikari.leak-detection-threshold=20000

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Connect and query with JDBC~1h
  2. 2
    Use PreparedStatement against SQL injection~1h
  3. 3
    Configure a HikariCP connection pool~1h

Key points

  • Always use PreparedStatement with ? placeholders; never concatenate user input into SQL.
  • Close connections, statements and result sets with try-with-resources.
  • With a pool, close() returns the connection for reuse instead of closing it.
  • Size the pool modestly; too many connections can overload the database.

Key terms

Tap a card to flip it. 0/6 known

Examples

java
String sql = "SELECT id, name FROM users WHERE email = ?";

try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement(sql)) {
  ps.setString(1, email);  // safe: value is never parsed as SQL
  try (ResultSet rs = ps.executeQuery()) {
    while (rs.next()) {
      System.out.println(rs.getLong("id") + " " + rs.getString("name"));
    }
  }
}

dataSource is a HikariDataSource, which Spring Boot configures by default.

Inserting a row and getting its new id

You insert a customer and need the generated id. Step 1: in PostgreSQL, add RETURNING id to the INSERT so the database sends back the new value. Step 2: because the statement now returns rows, run it with executeQuery. Step 3: read the id from the single result row. Step 4: try-with-resources closes the statement and returns the connection to the pool. The portable alternative is prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) with getGeneratedKeys().

java
long createCustomer(DataSource ds, String name, String email) throws SQLException {
  String sql = "INSERT INTO customers (name, email) VALUES (?, ?) RETURNING id";
  try (Connection conn = ds.getConnection();
       PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, name);
    ps.setString(2, email);
    try (ResultSet rs = ps.executeQuery()) {
      rs.next();
      return rs.getLong("id");
    }
  }
}

Moving money in one transaction

A transfer must debit one account and credit another, or do neither. Step 1: turn off auto-commit. Step 2: run both updates with the same connection. Step 3: if the debit touched no row because the balance was too low, throw, so the catch rolls back. Step 4: commit only when both succeed. Step 5: the finally block restores auto-commit before the connection goes back to the pool.

java
try (Connection c = ds.getConnection()) {
  c.setAutoCommit(false);
  try (var debit = c.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?");
       var credit = c.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
    debit.setBigDecimal(1, amount); debit.setLong(2, fromId); debit.setBigDecimal(3, amount);
    if (debit.executeUpdate() != 1) throw new SQLException("insufficient funds");
    credit.setBigDecimal(1, amount); credit.setLong(2, toId);
    credit.executeUpdate(); c.commit();
  } catch (SQLException e) {
    c.rollback();
    throw e;
  } finally {
    c.setAutoCommit(true);
  }
}

Quick reference

  • URL format: jdbc:postgresql://host:5432/dbname
  • Never concatenate input into SQL; use ? placeholders and setString or setLong
  • Placeholders cannot hold table or column names; use an allowlist
  • Indexes in JDBC start at 1 for both parameters and columns
  • rs.getObject("col", Long.class) returns null instead of 0 for SQL NULL
  • addBatch() plus executeBatch() cuts thousands of round trips to a few
  • HikariCP maximumPoolSize defaults to 10; total connections = pool size x instances
  • Spring 6.1+ JdbcClient gives a fluent API over JDBC with far less code

Common mistakes

  • Building SQL with string concatenation of user input.
  • Leaking connections by not closing them, exhausting the pool.
  • Setting a huge pool size thinking it always means more throughput.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A column is NULL and you call rs.getInt("score"). What do you get?

Question 2

2Users can sort a list by a column name they pick. How do you build the ORDER BY safely?

Question 3

3What is the default auto-commit mode of a new JDBC connection?

Question 4

4Four app instances each have a HikariCP pool of 30. PostgreSQL has max_connections = 100. What can happen?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a method that returns how many users have a given country code, using a PreparedStatement.

  2. Exercise 2medium

    Insert a list of 5,000 products efficiently with batching inside one transaction, sending a batch every 500 rows.

  3. Exercise 3hard

    Write findUsers(String sortBy, boolean desc) that lets callers sort by name, email or created_at only, and rejects anything else.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use plain JDBC or JPA?
JPA is productive for typical entity CRUD. Plain JDBC, or Spring's JdbcClient, is better for complex reporting SQL, bulk operations and when you want full control of each query; many apps use both.
Do I still need Class.forName to load the driver?
No. Since JDBC 4 drivers on the classpath register themselves automatically.
How big should my connection pool be?
Usually much smaller than people expect: start with HikariCP's default of 10 per instance, load test, and only grow it if threads wait for connections while the database still has spare capacity.
What is the difference between Statement and PreparedStatement?
Statement runs a fixed SQL string. PreparedStatement takes parameters separately, which prevents SQL injection and lets the database reuse the query plan.

Go deeper

ShareXLinkedInWhatsApp