Java › Standard

JDBC connections, pooling, and transaction boundaries

Trace JDBC driver discovery and HikariCP connection reuse, then verify a two-statement transfer rolls back on one shared connection.

JDBC connections, pooling, and transaction boundaries

A transaction belongs to a database connection. I use a failed transfer to trace how JDBC opens that connection, how a pool lends it out, and how Spring lets two repository calls participate in the same boundary.

The examples use Java 21, JDBC 4.3, HikariCP 6.x, and Spring Framework 6.x.

JDBC under the persistence framework

JPA providers and SQL mappers eventually need to send SQL to the database and read the returned rows. JDBC defines those interactions. The driver handles the database protocol. A DataSource is an injectable connection factory, while a Connection represents a database session and exposes commit() and rollback().

TypePackageResponsibility
Driverjava.sqlOpens a connection using the vendor protocol
DataSourcejavax.sqlProvides connections. A pool can implement it.
Connectionjava.sqlHolds session and transaction state
PreparedStatementjava.sqlBinds parameters and executes SQL
ResultSetjava.sqlReads rows from a result cursor

Keep supplied SQL values in bound parameters. A prepared statement does not make dynamically concatenated identifiers or SQL fragments safe. Those need validation or an explicit mapping to allowed fragments.

flowchart TD
    APP["Application and persistence framework"] --> API["JDBC API"]
    API --> POOL["DataSource or connection pool"]
    POOL --> DRIVER["Database driver"]
    DRIVER --> DB["Database"]

How the driver loads without Class.forName

A JDBC 4 driver can register through the Java service-provider mechanism. DriverManager discovers compatible providers through ServiceLoader when it initializes its drivers. The old explicit Class.forName() call is generally unnecessary when the driver JAR is visible to the relevant class loader.

1
2
3
# Path inside postgresql-42.7.x.jar
# META-INF/services/java.sql.Driver
org.postgresql.Driver

If a deployment says no suitable driver is available, inspect the runtime classpath and the JDBC URL. A missing driver and an unsupported URL look similar at that point. A shaded JAR that discards service descriptors can also break discovery.

Connecting pool lifetime to transaction lifetime

DriverManager can open a connection directly. A HikariDataSource usually lends a logical connection backed by a pooled physical session. Closing the logical connection returns it to the pool. Pool limits cap concurrent session use and can make application threads wait once the pool is full.

A Spring transaction manager can obtain a connection and bind it to the current thread through TransactionSynchronizationManager. Spring-aware access such as JdbcTemplate obtains that connection for the same data source. Code that calls a raw data source directly does not automatically participate. Calls on a different thread also need their own transaction handling.

sequenceDiagram
    participant S as Service proxy
    participant T as Transaction manager
    participant P as Hikari pool
    participant R as Repositories
    S->>T: Begin transaction
    T->>P: Borrow connection
    T->>T: Bind to the current thread
    S->>R: Execute both updates
    R-->>S: Return results
    S->>T: Commit or roll back
    T->>P: Release connection

Reproducing a transfer rollback

The standalone sample uses HikariCP and H2. The transfer borrows one connection, disables auto-commit, and passes that connection to both the withdrawal and deposit methods. It commits when both updates succeed and rolls back on failure. The account lookup uses a separate connection so the test can observe the committed result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build.gradle.kts
plugins {
    java
}

dependencies {
    implementation("com.zaxxer:HikariCP:6.2.1")
    runtimeOnly("com.h2database:h2:2.3.232")
    testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
}

tasks.test {
    useJUnitPlatform()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// src/main/java/com/example/jdbc/AccountTransferService.java
package com.example.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountTransferService {

    private final DataSource dataSource;

    public AccountTransferService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void transfer(long fromId, long toId, long amount) throws SQLException {
        try (Connection conn = dataSource.getConnection()) {
            boolean previousAutoCommit = conn.getAutoCommit();
            conn.setAutoCommit(false);

            try {
                withdraw(conn, fromId, amount);
                deposit(conn, toId, amount);
                conn.commit();
            } catch (Exception e) {
                conn.rollback();
                throw e;
            } finally {
                conn.setAutoCommit(previousAutoCommit);
            }
        }
    }

    private void withdraw(Connection conn, long accountId, long amount) throws SQLException {
        String sql = "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, amount);
            ps.setLong(2, accountId);
            ps.setLong(3, amount);
            if (ps.executeUpdate() != 1) {
                throw new IllegalStateException("Insufficient balance or missing account: id=" + accountId);
            }
        }
    }

    private void deposit(Connection conn, long accountId, long amount) throws SQLException {
        String sql = "UPDATE accounts SET balance = balance + ? WHERE id = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, amount);
            ps.setLong(2, accountId);
            if (ps.executeUpdate() != 1) {
                throw new IllegalStateException("Deposit account not found: id=" + accountId);
            }
        }
    }

    public long getBalance(long accountId) throws SQLException {
        String sql = "SELECT balance FROM accounts WHERE id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, accountId);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) {
                    throw new IllegalArgumentException("Account not found: id=" + accountId);
                }
                return rs.getLong("balance");
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// src/test/java/com/example/jdbc/AccountTransferServiceTest.java
package com.example.jdbc;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.Statement;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

class AccountTransferServiceTest {

    private HikariDataSource dataSource;
    private AccountTransferService service;

    @BeforeEach
    void setUp() throws Exception {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:h2:mem:jdbc_test;DB_CLOSE_DELAY=-1");
        config.setUsername("sa");
        config.setPassword("");
        config.setMaximumPoolSize(4);
        config.setLeakDetectionThreshold(3_000);

        dataSource = new HikariDataSource(config);
        service = new AccountTransferService(dataSource);

        try (Connection conn = dataSource.getConnection();
             Statement stmt = conn.createStatement()) {
            stmt.execute("DROP TABLE IF EXISTS accounts");
            stmt.execute("CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT NOT NULL)");
            stmt.execute("INSERT INTO accounts VALUES (1, 10000), (2, 5000)");
        }
    }

    @AfterEach
    void tearDown() {
        dataSource.close();
    }

    @Test
    void missingDepositAccountRollsBackWithdrawal() throws Exception {
        assertThrows(IllegalStateException.class, () -> service.transfer(1L, 999L, 3_000L));
        assertEquals(10_000L, service.getBalance(1L));
    }
}

Run ./gradlew test from the example project. The test asks the service to deposit into a missing account. After the failure, the source account balance must equal its initial value. If you put the two updates on independent auto-commit connections, this check would catch the partial withdrawal.

Diagnosing pool pressure and large reads

  • Use try-with-resources for the connection, statement, and result set. HikariCP leak detection can report a checkout stack during investigation. Tune the threshold above legitimate operation times to avoid noise.
  • PostgreSQL cursor fetching requires an appropriate positive fetch size and a transaction with auto-commit off. Check the driver-specific conditions. MySQL has separate streaming and cursor settings.
  • Keep database transaction scopes short. A network call inside an open transaction can hold a borrowed connection and locks while the remote service responds. Monitor active, idle, and waiting pool counts together.
  • For Spring MVC and JPA applications, review spring.jpa.open-in-view if requests keep a persistence context alive past the service boundary. Move required reads inside the intended transaction before turning it off.

References

Original Summary: The JDBC 4.0 API specification seeks to improve Java application access to SQL data stores by the provision of ease-of-development focused features and improvements at both the utility and API level. Using new Java language features planned for JSR-176 Java 2 Standard Edition 1.5, features such as annotations as defined in JSR-175, generics defined in JSR-014 in to addition to supplying a set of JDBC utility classes, SQL savvy developers will be able to more easily access SQL data sources while still benefiting from the full power of the JDBC API.
光 HikariCP・A solid, high-performance, JDBC connection pool at last. - brettwooldridge/HikariCP
This post is licensed under CC BY 4.0 by the author.