ExampleDifficulty: Intermediate2 min

Bridge in the Wild: JDBC Drivers

Your code talks to Connection and Statement; each database supplies the driver behind them.

JDBC, Java's database API, is a Bridge between the code that queries a database and the drivers that talk to each database. Application code is written against the interfaces in java.sql, such as Connection and PreparedStatement, and each database vendor ships a driver with its own classes behind them. The same query code runs on PostgreSQL, MySQL or an in-memory database by changing the URL.

The template's participants in JDBC
TemplateJDBC
AbstractionYour data-access code, such as countOrders, which holds a Connection
RefinedAbstractionOther data-access classes, each a variant on the same side
ImplementorThe java.sql interfaces: Connection, PreparedStatement, ResultSet
ConcreteImplementorA vendor driver's classes, such as PostgreSQL's connection class
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BrJdbc {
    static int countOrders(Connection connection, String customer) throws SQLException {
        String sql = "SELECT COUNT(*) FROM orders WHERE customer = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, customer);
            try (ResultSet rows = statement.executeQuery()) {
                rows.next();
                return rows.getInt(1);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("drivers registered: " + DriverManager.drivers().count());
        String url = "jdbc:postgresql://localhost/shop";
        try (Connection connection = DriverManager.getConnection(url)) {
            System.out.println("orders: " + countOrders(connection, "ana"));
        } catch (SQLException error) {
            System.out.println("SQLException: " + error.getMessage());
        }
    }
}
OutputRan with eclipse-temurin:21-jdk (Java 21.0.12)
drivers registered: 0
SQLException: No suitable driver found for jdbc:postgresql://localhost/shop
`countOrders` uses only `java.sql` types; `getConnection` picks a driver by the URL.

The listing ran in eclipse-temurin:21-jdk with no driver on the class path and no database. DriverManager found no registered driver able to handle a jdbc:postgresql: URL and refused, which shows where the bridge is crossed: the code chose nothing but a URL, and the driver behind it is found when the program runs. With PostgreSQL's driver added, the same code would return the count without a line changed.

countOrders never names a vendor class, which is what lets both sides vary. Drivers are rewritten and new databases are added without touching application code, and new data-access code is written without touching any driver.