JDBC: the four objects
Driver, Connection, Statement and the ResultSet that is a cursor — plus the getInt that turns NULL into zero.
Almost nobody writes JDBC directly any more — Spring Data, an ORM or a template sits on top. Knowing what those are sitting on is still worth an afternoon, because when a connection leaks, a ResultSet throws after its statement closed, or a nullable column silently becomes zero, the explanation is here and nowhere above it.
Four objects, and what each one owns
- Driver — knows how to speak one database's wire protocol. It registers itself when its jar is on the classpath; since JDBC 4 there is no
Class.forNameto write. - Connection — one session with the database. Expensive to create, which is the entire reason connection pools exist.
- Statement — one query in flight on that connection.
- ResultSet — a cursor over the rows, not a list of them.
The URL is what selects the driver: jdbc:postgresql://host:5432/db, jdbc:h2:mem:demo. Everything after the scheme is that driver's business.
Statement has two subtypes. PreparedStatement is the next lesson and the one you will use. CallableStatement calls a stored procedure — c.prepareCall("{call refund(?, ?)}") with OUT parameters registered by type and read back after execute() — and belongs to the Oracle and SQL Server shops where the logic lives in the database; in a service that owns its logic in Java you will meet it rarely, and mostly in code older than the service.
A ResultSet is a cursor, and it starts before the first row
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("select id, name, price from item order by id")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
}### columns: 3
### row -> 1 widget 1999
### row -> 2 bolt 250
### next() after the last row: falsenext() moves the cursor and returns whether it landed on a row. That is why the loop is while (rs.next()) and not while (rs.hasNext()) — there is no such method, and calling a getter before the first next() is an error rather than the first row.
The cursor may still be streaming from the server, which is why the next section matters more than it looks.
Everything closes, in reverse order
ResultSet, Statement and Connection all hold resources on both sides of the wire. try-with-resources closes them in reverse order of declaration, which is the order you want.
What happens when you let one escape:
ResultSet leaked;
try (Statement s = c.createStatement()) {
leaked = s.executeQuery("select id from item");
leaked.next(); // fine, inside
}
leaked.next(); // outside### inside the try, first id = 1
### SQLException: The object is already closed [90007-214]Closing a Statement closes its ResultSet. Closing a Connection closes everything on it. So a ResultSet is not something to return from a method — map it to your own objects while it is open, and hand back those.
getInt on a NULL column returns zero
This one is quiet and expensive:
### getInt(1) = 0
### wasNull() = true
### getObject(1)= nullThe primitive getters cannot return null, so they return 0, false, 0.0. A nullable price column becomes a price of zero, and nothing throws.
Two ways to be correct, and the second is usually better:
int price = rs.getInt("price");
if (rs.wasNull()) { /* it was NULL, not zero */ }
Integer price = (Integer) rs.getObject("price"); // null stays nullwasNull() refers to the last column read, so it has to be called immediately after the getter and before reading anything else. That ordering requirement is why getObject — or getObject(column, Integer.class) on modern drivers — is the safer habit.
Transactions are a Connection setting
JDBC is autocommit by default: every statement is its own transaction.
c.setAutoCommit(false);
try {
// several statements, one unit of work
c.commit();
} catch (SQLException e) {
c.rollback();
throw e;
}Two details worth carrying:
- Autocommit off is per connection, not per block. In a pool, a connection returned with autocommit still disabled poisons whoever gets it next — which is why frameworks reset it, and why hand-rolled pooling goes wrong.
- This is what
@Transactionalis doing. The proxy from the Spring course borrows a connection, turns autocommit off, runs your method, and commits or rolls back. Knowing that makes the self-invocation trap obvious rather than magical: no proxy, nosetAutoCommit(false), no transaction.
Reading what went wrong
SQLException carries more than a message, and the extra is what makes an error actionable:
getSQLState()— a five-character standard code.23505is a unique-constraint violation on PostgreSQL,23000the standard integrity-violation class.getErrorCode()— the database's own number, more specific and less portable.getNextException()— a chain. Batch failures in particular put the useful one further down, and aprintStackTrace()on the first can be nearly content-free.
Spring's DataAccessException hierarchy is a translation of exactly these into vendor-neutral types — DuplicateKeyException rather than state 23505 — which is most of what JdbcTemplate buys you beyond the boilerplate.
What you will actually use
For anything but a script, use the layer above:
JdbcTemplate— JDBC without the closing, the checked exceptions or the loop.queryForObject,querywith aRowMapper,update.JdbcClient(Spring 6.1+) — the same with a fluent API.- JPA — when you want entities and a persistence context, with everything that course described.
None of them removes what is on this page. They make the correct thing the default, and the failures underneath still surface with these names.
Under the hood: what the driver does on the wire, and what a pool actually hands you
JDBC is a Java-side contract. Underneath it, a Connection is a socket speaking that database's wire protocol — PostgreSQL's, MySQL's, whatever the URL named — and the driver's whole job is translating your Statement/ResultSet calls into that protocol's messages and back. That is why the URL scheme selects a jar and nothing else in this lesson changes across databases: the JDBC API is the same, the bytes on the socket are not.
A ResultSet is not necessarily "the rows the driver already has." Whether next() reads from memory or makes the connection do more work depends on fetch size. By default, most drivers pull the entire result set across the wire on executeQuery() and next() just walks an in-memory buffer — which is fine for twelve rows and a problem for twelve million, because the driver (and your heap) is holding all of them before your loop sees the first one. Calling ps.setFetchSize(n) asks the driver to fetch in chunks of n instead, so next() occasionally triggers another round trip to refill the buffer rather than one giant one up front. The exact mechanics are driver-specific and worth checking against your own: PostgreSQL's driver only honours a fetch size when autocommit is off (a server-side cursor is a transactional object); some other drivers need a specific combination of result-set type and a "streaming" flag before they will hold back rows at all. The behavior described in "the cursor may still be streaming" earlier in this lesson is real, but it is not the default everywhere — check before assuming a large query streams.
What a pool hands you from getConnection() is not the physical connection. HikariCP and friends return a proxy object that implements java.sql.Connection but wraps a real one underneath. Calling close() on that proxy does not close the socket — it runs the pool's own logic, which resets state (autocommit, any leftover transaction) and returns the physical connection to the idle set for someone else to borrow. This is exactly what makes try-with-resources safe to use unconditionally with a pooled DataSource: "closing" a connection you got from a pool is really "giving it back," and the JDBC contract lets the pool intercept that call because your code only ever holds an interface reference, never the concrete class.
Try it yourself
Trace what "closing" a pooled connection really does
A service borrows a connection from a pool of 3, runs a query, and returns it — three times in a row, sequentially, never holding two at once.
int idle = 3;
for (int i = 1; i <= 3; i++) {
idle--; // borrow: proxy handed out, physical connection leaves the idle set
System.out.println("borrow " + i + " -> pool idle: " + idle);
idle++; // "close()" on the proxy: the pool intercepts it and re-adds the physical connection
System.out.println("return " + i + " -> pool idle: " + idle);
}If close() on a pooled Connection actually closed the socket, what would have to happen instead on the next getConnection() call, and why is that slower than what the pool does?
A closed socket means a new one, which means the driver's connect handshake again
If close() genuinely tore down the TCP connection, the next getConnection() would have to open a fresh socket, run the database's authentication handshake, and set up a new session — the exact per-request cost that pools exist to amortize away. Because close() on the proxy only returns the physical connection to the idle set, the next borrow gets a socket that is already authenticated and ready, and the only cost is handing out a reference. This is also why a pool that gives you back a genuinely fresh connection from the operating system's socket layer on every single call is not really pooling — it is a DataSource in name only.
Misconceptions
- "A
ResultSetholds all the rows from the query as soon asexecuteQuery()returns." Only if the driver fetched them all up front, which is the common default — but it is a default, not a guarantee, and it changes withsetFetchSize()and, for some drivers, with autocommit and result-set type. Code that assumes an unbounded query is "already in memory and therefore safe to iterate twice" can be wrong depending on driver configuration. - "Calling
connection.close()on a connection from a pooledDataSourcecloses the database session." It returns the connection to the pool. The physical session stays open, which is the entire point — and it is also why a connection returned withautoCommit(false)still set poisons the next borrower if the pool (or your code) does not reset it.
Sources
- Java SE documentation —
java.sql.Connection,java.sql.Statement#setFetchSize. - PostgreSQL JDBC driver documentation — "Getting results based on a cursor" (fetch size and autocommit).
- HikariCP wiki — "About Pool Sizing" and the
leakDetectionThresholdconfiguration.