Stage 9: JDBC, JPA and Hibernate, lesson 1 of 6

JDBC: talking to databases

Intermediate3 min read@since 7Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

JDBC (since JDK 1.1) is the low-level API that every Java database tool builds on, including Hibernate and Spring Data.

The core pieces: a DataSource gives you a Connection, which creates a PreparedStatement, which returns a ResultSet.

Always use PreparedStatement with ? placeholders. It prevents SQL injection and lets the database reuse query plans.

Real apps use a connection pool (HikariCP is Spring Boot's default) to reuse open connections, because opening a new database connection takes milliseconds.

Example

Java
String sql = "SELECT id, title, price FROM course WHERE price < ? ORDER BY price";

try (Connection con = dataSource.getConnection();
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setBigDecimal(1, new BigDecimal("999"));
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            System.out.printf("%d %s %s%n",
                rs.getLong("id"), rs.getString("title"), rs.getBigDecimal("price"));
        }
    }
}

// Spring Boot 3.2+: JdbcClient removes most of the boilerplate
List<Course> cheap = jdbcClient.sql("SELECT * FROM course WHERE price < :max")
    .param("max", 999)
    .query(Course.class)
    .list();

Common mistake

Building SQL by concatenating user input ("... WHERE name = '" + name + "'"). That's SQL injection. Always bind parameters.

Under the hood

JDBC transactions: con.setAutoCommit(false), then commit() or rollback(). Batch inserts with addBatch() and executeBatch() cut network round trips dramatically. Spring's JdbcTemplate and JdbcClient manage resources for you and translate SQLException into Spring's unchecked DataAccessException hierarchy.

Check yourself

What mainly protects against SQL injection?

How this connects

Part of Job-ready backend developer.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.