Skip to main content
PreparationZone Logo
PrepZone

JdbcTemplate, JPA Architecture, and Entity Lifecycle

SQL with JdbcTemplate, the persistence context, and transient, managed, detached, and removed states.

Pass checkpoint below

Why this matters

  • Interviews start with "why not just use JDBC?" — you need a crisp comparison, not a slogan that JPA is always better.
  • Entity lifecycle (transient, managed, detached, removed) explains LazyInitializationException, duplicate inserts, and "I updated the field but the row did not change."
  • BookStore reporting queries often stay on JdbcTemplate while the write model stays on JPA. Knowing both is normal production work.

JdbcTemplate

L1 · Fresher

JdbcTemplate executes SQL, binds parameters, and translates SQLException into Spring's DataAccessException hierarchy.

JPA architecture

L2 · Intermediate

Your repository talks to an EntityManager. Hibernate is the provider. The persistence context is the in-memory set of managed entities for one transaction.

Entity states

L3 · Advanced

A new Book() is transient. save makes it managed. Leaving the transaction detaches it. delete schedules removal at flush.

When JDBC still wins

L4 · Expert

Bulk reports, database-specific SQL, and one-off migrations are clearer as JdbcTemplate or native queries than as a tangled entity graph.

JDBC without a template

Raw JDBC forces you to open a connection, prepare a statement, walk a ResultSet, and close everything:

Java
try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement(
         "SELECT id, title, price FROM books WHERE isbn = ?")) {
    ps.setString(1, isbn);
    try (ResultSet rs = ps.executeQuery()) {
        if (!rs.next()) {
            throw new BookNotFoundException(isbn);
        }
        return new BookRow(rs.getLong("id"), rs.getString("title"), rs.getBigDecimal("price"));
    }
}

Leaked connections and checked SQLException are the usual bugs. Spring's JdbcTemplate owns that boilerplate.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 3 sections

  • JdbcTemplate in BookStore
  • JPA setup in Boot 3.5
  • Entity lifecycle

Test yourself

Answer these before moving on — recall is what makes it stick.