The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·49

Persistence — JDBC, JPA, Hibernate and Spring Data

How Java talks to relational databases, from JDBC and JdbcClient up to JPA and Hibernate. Covers the entity lifecycle, the persistence context and dirty checking, lazy versus eager loading, transactions (propagation, isolation, read-only, rollback rules), Spring Data repositories, derived queries, JPQL, native SQL, Specifications and projections. Then the nuances that cause production incidents: N+1 queries, fetch joins, pagination with joins, optimistic locking, batching and connection pools. Compared with EF Core, SQLAlchemy, Ecto, sqlx, sqlc, Diesel, GORM and Prisma.

34 topics · ~33 min read · 31-question quiz
Updated Suggest a correction

Start here: from objects to rows and back

The gap between objects and tables

A Java application thinks in objects (an Order holding a list of OrderLines, each pointing to a Dish); a relational database stores rows in tables linked by keys. Persistence code moves data across that gap. Java offers it in layers, each built on the one below:

Layer What you write Example
JDBC SQL strings; you copy columns into objects ps.setLong(1, id); rs.getString("name")
Spring's JdbcClient SQL, with less boilerplate and Spring transactions jdbc.sql("…").param(id).query(Dish.class).list()
JPA (Hibernate) Annotated classes; SQL generated for you @Entity class Dish, em.find(Dish.class, 42)
Spring Data JPA Repository interfaces; queries derived from method names List<Dish> findByPriceLessThan(long max)

Every layer above JDBC ends up sending SQL through JDBC, so the problems in this chapter (too many queries, slow inserts, lost updates, exhausted connections) look the same whichever layer you use. Learn the bottom layer first; then the higher ones become shortcuts you can see through. Other ecosystems have the same stack: Go's database/sql, sqlc and GORM; .NET's ADO.NET, Dapper and Entity Framework; Python's DB-API and SQLAlchemy; Rust's sqlx and Diesel; Node's pg, Knex and Prisma.

JDBC: SQL in, records out

Java
record Dish(long id, String name, long pricePaise) {}

List<Dish> cheaperThan(long max) throws SQLException {
    try (PreparedStatement ps = c.prepareStatement("SELECT id, name, price_paise FROM dish WHERE price_paise < ? ORDER BY price_paise")) {
        ps.setLong(1, max);
        try (ResultSet rs = ps.executeQuery()) {
            List<Dish> out = new ArrayList<>();
            while (rs.next()) out.add(new Dish(rs.getLong("id"), rs.getString("name"), rs.getLong("price_paise")));
            return out;
        }
    }
}
Text
1) dishes under ₹60: [Dish[id=3, name=Filter coffee, pricePaise=3000], Dish[id=2, name=Idli, pricePaise=5000]]

A connection (from DriverManager here, from a pool in real applications) carries prepared statements whose ? placeholders are filled with typed values; a result set is walked row by row and each row copied into an object. try (…) closes statements and result sets, which hold resources on both sides.

Transactions: all or nothing

Java
c.setAutoCommit(false);
try {
    insert the order; insert line 1 (dish 1); insert line 2 (dish 99, which doesn't exist)
    c.commit();
} catch (SQLException e) {
    c.rollback();
}
Text
2) order failed and was rolled back: ERROR: insert or update on table "order_line" violates foreign key constraint "order_line_dish_id_fkey"
   rows left behind: orders 0, order lines 0

By default every statement commits on its own (autocommit). Turning it off makes the following statements one transaction: either commit makes them all permanent or rollback undoes them all, so a failure halfway never leaves an order without its lines. In Spring you rarely call these yourself: @Transactional on a service method does it (a proxy, chapter 46, so the self-invocation rule applies).

Never build SQL from input

Java
String evil = "x' OR '1'='1";
s.executeQuery("SELECT count(*) FROM dish WHERE name = '" + evil + "'");          // concatenated
ps = c.prepareStatement("SELECT count(*) FROM dish WHERE name = ?"); ps.setString(1, evil);
Text
3) concatenated SQL with name = x' OR '1'='1 matched 3 dishes
   prepared statement with the same input matched 0

Concatenation let the input rewrite the query (SQL injection, still in the OWASP Top 10; Volume 10). A placeholder sends the value separately from the SQL text, so it can only ever be a value. Every layer above JDBC uses placeholders for you, except where you concatenate strings into native or JPQL queries yourself.

Let the database enforce rules

Text
4) duplicate name: 23505 ERROR: duplicate key value violates unique constraint "dish_name_key"
   zero price: 23514 ERROR: new row for relation "dish" violates check constraint "dish_price_paise_check"

UNIQUE, CHECK, NOT NULL and foreign keys hold even when two requests race each other or someone runs a script against the database, which application-level checks can't guarantee. The SQLSTATE codes (23505 unique violation, 23514 check, 23503 foreign key) let the service map them to 409 or 422 responses.

What JPA adds

With JPA you annotate classes instead of writing SQL for each operation:

Java
@Entity class Dish {
    @Id @GeneratedValue Long id;
    String name;
    long pricePaise;
    @Version int version;                    // optimistic locking
}
@Entity class Order {
    @Id @GeneratedValue Long id;
    @OneToMany(mappedBy = "order") List<OrderLine> lines;      // loaded lazily, on first access
}
interface DishRepository extends JpaRepository<Dish, Long> { List<Dish> findByPricePaiseLessThan(long max); }

Hibernate generates the INSERT, UPDATE and SELECT statements, tracks which loaded objects changed and writes them at commit (dirty checking), loads related objects on demand (lazy loading), and caches objects within a transaction (the persistence context). That removes most boilerplate, and hides the SQL: the lab's first experiment shows how lazily loading 200 orders' lines turns one screen into 201 queries, the N+1 problem, which is the most common performance bug in ORM-based applications. Turn on SQL logging in development (spring.jpa.show-sql, or better, a statistics or datasource-proxy logger) so you always know what's being sent.

How deep to go in persistence

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Query and update with JDBC prepared statements; explain transactions
L2 Map entities with JPA, write Spring Data repositories, use @Transactional correctly
L3 Explain the persistence context, lazy loading, flush, fetch strategies, optimistic locking, batching and pools, and other ecosystems' equivalents
L4 Diagnose N+1 queries, slow bulk writes, lost updates, pool exhaustion and long transactions from SQL logs and metrics
L5 Choose data-access approaches per use case (ORM, SQL-first, projections, CQRS reads)
L6 Set data-access standards, migration practices and performance budgets across services

Talking to the database

The persistence stack

Text
your code
  ↓ Spring Data repositories (interfaces → generated implementations)
  ↓ JPA API (EntityManager, JPQL, Criteria)            or   JdbcClient / JdbcTemplate / jOOQ
  ↓ Hibernate ORM (JPA provider: mapping, persistence context, SQL generation)
  ↓ JDBC API (Connection, PreparedStatement, ResultSet)
  ↓ connection pool (HikariCP)
  ↓ JDBC driver (PostgreSQL, MySQL, Oracle…) → database wire protocol over TCP

Each layer adds convenience and hides cost. Most persistence performance problems come from not knowing what the layer above generates beneath it. Vol. 4 covers databases themselves: indexes, query plans, isolation anomalies and locking.

JDBC

JDBC is Java's low-level database API: open a connection, prepare a statement with bind parameters, execute it, and iterate the result set.

Java
String sql = "SELECT id, status, total FROM orders WHERE customer_id = ? AND created_at >= ?";
try (Connection c = dataSource.getConnection();                       // from the pool
     PreparedStatement ps = c.prepareStatement(sql)) {
    ps.setString(1, customerId);                                       // bind parameters: no SQL injection,
    ps.setObject(2, since);                                            // and the DB can reuse the plan
    try (ResultSet rs = ps.executeQuery()) {
        List<OrderRow> out = new ArrayList<>();
        while (rs.next()) {
            out.add(new OrderRow(rs.getString("id"), rs.getString("status"), rs.getBigDecimal("total")));
        }
        return out;
    }
}   // try-with-resources returns the connection to the pool even on exceptions

The boilerplate (resources, exceptions, mapping) is why Spring offers JdbcTemplate and, since Spring 6.1, the fluent JdbcClient:

Java
@Repository
class OrderQueries {
    private final JdbcClient jdbc;
    OrderQueries(JdbcClient jdbc) { this.jdbc = jdbc; }

    List<OrderRow> recent(String customerId, Instant since) {
        return jdbc.sql("""
                SELECT id, status, total FROM orders
                 WHERE customer_id = :customerId AND created_at >= :since
                 ORDER BY created_at DESC LIMIT 50
                """)
            .param("customerId", customerId)
            .param("since", Timestamp.from(since))
            .query(OrderRow.class)                       // maps columns to record components by name
            .list();
    }

    int markShipped(String id) {
        return jdbc.sql("UPDATE orders SET status = 'SHIPPED', version = version + 1 WHERE id = :id AND status = 'PAID'")
            .param("id", id).update();                   // affected rows: 0 means the precondition failed
    }
}

Spring translates vendor SQLExceptions into its unchecked DataAccessException hierarchy (DuplicateKeyException, DataIntegrityViolationException, CannotAcquireLockException, QueryTimeoutException…), so you can handle "duplicate key" portably. Plain JDBC or JdbcClient is often the right choice for read-heavy queries, reports, bulk operations and anything where you want exact SQL control. Many teams combine JPA for writes to aggregates with JdbcClient or jOOQ for queries (a light form of CQRS). Spring Data JDBC is a simpler alternative to JPA: aggregates are mapped without a persistence context, lazy loading or dirty checking, and saving writes the whole aggregate.

JPA and Hibernate

JPA mapping basics

JPA (Jakarta Persistence) is a specification of an object-relational mapper (ORM). Hibernate is its dominant implementation, at version 7 with Spring Boot 4. You annotate classes as entities mapped to tables:

Java
@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
    @SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)   // batch-friendly IDs
    private Long id;

    @Version                                         // optimistic locking (below)
    private long version;

    @Column(nullable = false, length = 40)
    private String customerId;

    @Enumerated(EnumType.STRING)                     // never ORDINAL (chapter 33)
    private Status status = Status.PENDING;

    @Embedded
    private Money total;                             // a value object mapped into columns of this table

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)   // composition (chapter 34)
    @OrderColumn(name = "line_no")
    private List<OrderLine> lines = new ArrayList<>();

    @ManyToOne(fetch = FetchType.LAZY)               // ALWAYS lazy for to-one (the default is EAGER!)
    @JoinColumn(name = "shipping_address_id")
    private Address shippingAddress;

    protected Order() {}                             // JPA needs a no-arg constructor (can be protected)

    public Order(String customerId) { this.customerId = customerId; }

    public void addLine(String sku, int qty, Money unitPrice) {   // keep both sides of the association in sync
        var line = new OrderLine(this, sku, qty, unitPrice);
        lines.add(line);
        recalculate();
    }
    public void pay() {
        if (status != Status.PENDING) throw new IllegalStateException("not payable: " + status);
        status = Status.PAID;
    }
    // equals/hashCode: see "entity identity" below
}

@Entity
class OrderLine {
    @Id @GeneratedValue Long id;
    @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "order_id") Order order;   // owning side
    String sku; int qty;
    @Embedded Money unitPrice;
    protected OrderLine() {}
    OrderLine(Order o, String sku, int qty, Money p) { this.order = o; this.sku = sku; this.qty = qty; this.unitPrice = p; }
}

Mapping notes:

  • Owning side: in a bidirectional association, the side with the foreign key (@ManyToOne / @JoinColumn) owns it. mappedBy marks the inverse side, and changes only to the inverse side aren't persisted. Keep both sides consistent with helper methods.
  • ID generation: IDENTITY (auto-increment) forces an immediate INSERT to learn the ID and disables JDBC insert batching. SEQUENCE with an allocationSize (pooled optimiser) lets Hibernate assign IDs in memory and batch inserts. UUIDs (v7 for index locality) can be generated client-side.
  • Records can't be entities (entities need mutability, no-arg constructors and proxyable classes), but records work as @Embeddable values (Hibernate 6.2+) and as DTO projections.
  • Prefer schema migrations (Flyway/Liquibase) over hibernate.ddl-auto=update in anything but throwaway prototypes. Use ddl-auto=validate to check that mappings match the schema.

Entity lifecycle and the persistence context

The persistence context (EntityManager / Hibernate Session) is a unit of work plus an identity map for one transaction (by default):

Interactive diagram: Inside one transaction: what the persistence context does. It needs JavaScript; the text around it says the same.
transientnew Order() MANAGEDdirty-checkedflushed at commit detachedcontext closed removedDELETE at flush persist() close merge() remove() find() / query one persistence context per transaction (Spring default):the same row → the same Java object (identity map)
JPA entity states. persist makes a transient object managed; managed entities are tracked and flushed; when the persistence context closes they become detached; merge copies detached state into a managed instance; remove schedules deletion.

Key behaviours:

  • Identity map (first-level cache): within one persistence context, loading the same row twice returns the same object, and find() doesn't hit the database the second time.
  • Dirty checking: Hibernate snapshots each managed entity's state when it's loaded. At flush time it compares current with snapshot and issues UPDATEs for changed entities. You never call save() to update a managed entity: changing a field inside a transaction is enough.
Java
@Transactional
public void pay(Long orderId) {
    Order o = orders.findById(orderId).orElseThrow();   // managed
    o.pay();                                            // just mutate…
}                                                       // …commit → flush → UPDATE orders SET status=?, version=? WHERE id=? AND version=?
  • Flush sends pending SQL to the database. It happens at commit, before queries whose results might be affected (FlushMode.AUTO), or explicitly (flush()). Statements are reordered and batched by Hibernate (inserts, then updates, then deletes, roughly), so database errors such as constraint violations may surface at flush or commit, not at the line that caused them.
  • Detached entities: after the context closes, entities are plain objects. Changes aren't tracked, and touching an uninitialised lazy association throws LazyInitializationException.
  • merge() copies a detached object's state onto a managed instance and returns the managed one; the argument stays detached. Spring Data's save() calls persist() for new entities and merge() for ones it considers existing (by checking the ID or version). Calling save() on an already managed entity is redundant.
  • Memory: the persistence context holds every entity loaded in the transaction plus its snapshot. A batch job loading 1M entities in one transaction will run out of memory. Process in chunks with flush(); clear();, use a StatelessSession, or use JDBC.

Lazy and eager loading

Associations can be loaded eagerly (with the owner) or lazily (on first access, through a proxy for to-one associations or a persistent collection wrapper for to-many).

Association JPA default Recommendation
@ManyToOne, @OneToOne EAGER Set LAZY explicitly (@OneToOne lazy on the inverse side needs bytecode enhancement or @MapsId)
@OneToMany, @ManyToMany LAZY Keep it LAZY
@ElementCollection LAZY Keep it LAZY

Make everything lazy, then fetch what each use case needs explicitly (fetch joins, entity graphs or DTO queries). EAGER defaults are a performance trap: every query for OrderLine would also load its Order, then that order's EAGER Customer, and so on, often through extra queries, and you can't turn EAGER off per query.

Open Session in View (OSIV): Spring Boot enables spring.jpa.open-in-view=true by default (with a startup warning). It keeps the persistence context open for the whole web request, so lazy loading works during JSON serialisation in the controller. It "fixes" LazyInitializationException by hiding N+1 queries in the view layer and holding a database connection for the entire request. Disable it (spring.jpa.open-in-view=false) and fetch explicitly in the service layer, mapping to DTOs inside the transaction.

Transactions

@Transactional (Spring's, from org.springframework.transaction.annotation) demarcates transactions declaratively via an AOP proxy (chapter 46: mind self-invocation, and that it only works on public methods called from outside, unless you use AspectJ):

Java
@Service
public class OrderService {
    @Transactional                                          // read-write transaction
    public Order place(PlaceOrder cmd) { … }

    @Transactional(readOnly = true)                         // hints: no flush, Hibernate skips snapshots, read replica routing possible
    public OrderDto find(Long id) { … }

    @Transactional(propagation = Propagation.REQUIRES_NEW)  // suspend the outer transaction, run independently
    public void recordAuditFailure(…) { … }                 // (must be on ANOTHER bean to take effect!)

    @Transactional(isolation = Isolation.REPEATABLE_READ, timeout = 5,
                   rollbackFor = PaymentException.class)    // checked exceptions don't roll back by default!
    public void settle(…) throws PaymentException { … }
}

Propagation (what happens when a transactional method calls another):

Propagation Behaviour
REQUIRED (default) Join the current transaction, or start one
REQUIRES_NEW Always start a new, independent transaction (suspending the current one). It commits or rolls back on its own. It uses a second connection, so pool exhaustion deadlocks are possible under load
NESTED A savepoint within the current transaction (JDBC savepoints; not supported with JPA's transaction manager)
SUPPORTS / NOT_SUPPORTED / NEVER / MANDATORY Join if present / suspend / fail if present / fail if absent

Rollback rules: by default Spring rolls back on unchecked exceptions (RuntimeException, Error) and commits on checked exceptions, an EJB-era convention that surprises people. Use rollbackFor, or keep domain exceptions unchecked. Catching an exception inside a transactional method and continuing doesn't help if an inner REQUIRED method already marked the transaction rollback-only: you'll get UnexpectedRollbackException at commit.

Isolation: Spring passes the level to the database (READ_COMMITTED is the default in PostgreSQL and Oracle; MySQL InnoDB defaults to REPEATABLE_READ). Vol. 4 covers the anomalies each level allows (dirty reads, non-repeatable reads, phantoms, write skew) and how MVCC implements them.

Transaction hygiene:

  • Keep transactions short. Never make remote calls (HTTP, payments, email) inside a database transaction: you hold locks and a pooled connection while waiting on the network, and a rollback can't undo the remote side effect. Do remote work before or after, and use the outbox pattern for reliable side effects (chapter 51).
  • Put @Transactional on service methods (use cases), not on controllers or repositories individually.
  • readOnly = true for query methods: Hibernate skips dirty checking (less memory and CPU), and routing data sources can send them to replicas.
  • Programmatic alternative: TransactionTemplate (tx.execute(status -> …)) when you need finer control or must avoid proxy limitations.

Entity identity, equals and hashCode

Entities are tricky for equals/hashCode (chapter 35) because the ID is often null until persisted, and Hibernate may hand you proxies whose class is a subclass. A robust pattern:

Java
@Override public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Order other)) return false;                  // instanceof works with Hibernate proxies (subclasses)
    return id != null && id.equals(other.getId());                  // use the getter: proxy fields may be uninitialised
}
@Override public int hashCode() { return Order.class.hashCode(); }  // constant: stable before and after persist

Alternatives: a natural key (an immutable business identifier) or application-assigned IDs (UUIDv7 assigned in the constructor), which make equality trivial and enable inserts without database round trips. Avoid Lombok's @Data/@EqualsAndHashCode on entities: they include every field and touch lazy associations.

Spring Data

Repositories and derived queries

Spring Data generates repository implementations from interfaces. The same programming model covers JPA, JDBC, MongoDB, Redis, Cassandra, Elasticsearch, R2DBC and more:

Java
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {

    // Derived queries: parsed from the method name at startup
    List<Order> findByCustomerIdAndStatusOrderByCreatedAtDesc(String customerId, Status status);
    Optional<Order> findFirstByCustomerIdOrderByCreatedAtDesc(String customerId);
    boolean existsByCustomerIdAndStatus(String customerId, Status status);
    long countByStatus(Status status);
    Page<Order> findByStatus(Status status, Pageable pageable);          // + a COUNT query
    Slice<Order> findByCustomerId(String customerId, Pageable pageable); // no count; knows whether there's more
    Window<Order> findFirst50ByStatusOrderByIdAsc(Status s, ScrollPosition pos);   // keyset scrolling (chapter 45)
    Stream<Order> streamByStatus(Status status);                         // must be closed, inside a transaction

    // JPQL: queries over ENTITIES and fields, not tables and columns
    @Query("select o from Order o where o.total.amount > :min and o.status in :statuses")
    List<Order> findBig(@Param("min") BigDecimal min, @Param("statuses") Set<Status> statuses);

    // Fetch join to load lines in the same query (avoids N+1)
    @Query("select distinct o from Order o left join fetch o.lines where o.id = :id")
    Optional<Order> findWithLines(@Param("id") Long id);

    // Entity graph: declarative fetch plan
    @EntityGraph(attributePaths = {"lines", "shippingAddress"})
    List<Order> findByCustomerId(String customerId);

    // Native SQL: full database power (window functions, CTEs, JSON operators, upserts)
    @Query(value = """
        SELECT o.* FROM orders o
         WHERE o.customer_id = :customerId
           AND o.created_at > now() - interval '30 days'
        """, nativeQuery = true)
    List<Order> recentNative(@Param("customerId") String customerId);

    // Bulk update: bypasses the persistence context. clearAutomatically avoids stale managed entities
    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query("update Order o set o.status = 'EXPIRED' where o.status = 'PENDING' and o.createdAt < :cutoff")
    int expire(@Param("cutoff") Instant cutoff);
}

Long derived-query names are a smell. Past two or three conditions, use @Query, a Specification or Querydsl, or a dedicated query class with JdbcClient/jOOQ.

Specifications and dynamic queries

For search screens with optional filters, use the Criteria API wrapped in Specifications (composable predicates):

Java
final class OrderSpecs {
    static Specification<Order> hasStatus(Status s) { return (root, q, cb) -> s == null ? null : cb.equal(root.get("status"), s); }
    static Specification<Order> customer(String id) { return (root, q, cb) -> id == null ? null : cb.equal(root.get("customerId"), id); }
    static Specification<Order> createdAfter(Instant t) { return (root, q, cb) -> t == null ? null : cb.greaterThanOrEqualTo(root.get("createdAt"), t); }
}
// null predicates are ignored, so filters compose naturally
Page<Order> page = orders.findAll(
    Specification.where(hasStatus(f.status())).and(customer(f.customerId())).and(createdAfter(f.since())),
    PageRequest.of(0, 50, Sort.by(Sort.Order.desc("createdAt"), Sort.Order.asc("id"))));

Alternatives with better type safety: Querydsl (generated QOrder classes) and jOOQ (SQL-first and fully type-safe, generated from the database schema). The JPA static metamodel (Order_.status) adds type safety to Criteria.

Projections

Don't load entire entities, with their associations and dirty-check snapshots, just to show a list. Project to exactly what's needed:

Java
// Interface projection (Spring Data creates a proxy; nested properties supported)
interface OrderSummary { Long getId(); Status getStatus(); BigDecimal getTotalAmount(); }
List<OrderSummary> findSummariesByCustomerId(String customerId);

// Class/record (DTO) projection via a JPQL constructor expression: selects ONLY these columns
record OrderRow(Long id, Status status, BigDecimal total) {}
@Query("select new com.shop.orders.OrderRow(o.id, o.status, o.total.amount) from Order o where o.customerId = :c")
List<OrderRow> rows(@Param("c") String customerId);

// Dynamic projection: the caller chooses the type
<T> List<T> findByStatus(Status status, Class<T> type);

DTO projections are not managed: there's no dirty checking, no snapshots, and no lazy-loading surprises. They're the right tool for read paths and APIs.

The nuances that cause incidents

The N+1 query problem

The most common ORM performance bug. One query loads N parents, then each lazy association access triggers one more query per parent:

N+1 SELECT * FROM orders … (1) for o in orders: o.getLines() SELECT … WHERE order_id = 1 SELECT … WHERE order_id = 2 … ×100 → 101 round trips join fetch / @EntityGraph1 query (rows multiply) batch fetching1 + ⌈N/size⌉ queries, IN (…) DTO projection: 1 query invisible in code review; visible as many tiny queries in SQL logs 101 × 1 ms = 101 ms of round trips before any real work
The N+1 problem. Loading 100 orders and touching each order's lines issues 101 queries; a fetch join or batch fetching collapses them into one or two.
Java
List<Order> orders = repo.findByStatus(Status.PAID);           // 1 query
for (Order o : orders) total += o.getLines().size();            // +1 query per order (lazy collection initialisation)
// Also hidden in: JSON serialisation of entities, toString(), mappers walking associations, OSIV views.

Detection: log SQL in development (spring.jpa.show-sql is crude; better are logging.level.org.hibernate.SQL=debug plus bind parameters, or datasource-proxy / p6spy), Hibernate statistics (hibernate.generate_statistics=true), APM traces showing repeated similar queries, or tests asserting query counts (the Hypersistence Utils SQLStatementCountValidator, or Spring's @AutoConfigureTestDatabase with datasource-proxy).

Fixes:

  1. Fetch join in JPQL (join fetch) or an @EntityGraph for the use case that needs the association.
  2. Batch fetching: spring.jpa.properties.hibernate.default_batch_fetch_size=50 makes Hibernate initialise lazy collections and proxies for up to 50 parents at once with WHERE order_id IN (…). That's a cheap global safety net turning N+1 into 1 + N/50.
  3. DTO projections with joins or aggregates computed in SQL (count(l), sum(l.qty)), often the best fix for read paths.
  4. A @BatchSize annotation on specific associations, or @Fetch(FetchMode.SUBSELECT).

The same problem exists in every ORM: EF Core (Include, split queries), SQLAlchemy (selectinload, joinedload, and lazy="raise" to forbid implicit loads), Rails ActiveRecord (includes, the Bullet gem), Django (select_related, prefetch_related), Prisma (include, which batches), GORM (Preload). Ecto (Elixir) has no lazy loading at all: an association is %Ecto.Association.NotLoaded{} until you explicitly Repo.preload it, which makes N+1 visible instead of implicit. Many teams consider that the best design choice in ORM history.

Fetch joins and their limits

  • Row multiplication: joining a collection returns one row per child. An order with 10 lines comes back 10 times in the result set. Hibernate 6+ de-duplicates parent entities automatically (distinct isn't needed in the Java result), but the SQL still transfers the duplicated parent columns.
  • Multiple collection fetch joins (join fetch o.lines join fetch o.payments) create a Cartesian product (lines × payments rows). Hibernate throws MultipleBagFetchException for two List (bag) collections. Using Sets avoids the exception but not the explosion. Fetch one collection per query (several queries), or use batch fetching for the others.
  • Filtering a fetch-joined collection (join fetch o.lines l where l.qty > 1) produces partially initialised collections that look complete. That's dangerous if the entity is later modified and flushed. Use a DTO query instead.

Pagination with joins

Combining join fetch of a collection with setMaxResults/Pageable can't be done in SQL correctly, because LIMIT would cut rows, not parents. Hibernate fetches all rows and paginates in memory, logging warning HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory. With large tables that's an outage waiting to happen. Hibernate can be told to fail instead: hibernate.query.fail_on_pagination_over_collection_fetch=true.

The correct pattern is two queries:

Java
@Query("select o.id from Order o where o.status = :status")              // 1. page of IDs (uses LIMIT/OFFSET or keyset)
Page<Long> pageIds(@Param("status") Status status, Pageable pageable);

@Query("select o from Order o left join fetch o.lines where o.id in :ids")   // 2. fetch those parents with children
List<Order> findWithLines(@Param("ids") Collection<Long> ids);
// Re-sort step 2's results by the order of the IDs from step 1. Or rely on batch fetching instead of join fetch.

Optimistic locking

Two users load order 42 at version 7. Both modify it. Without protection, the second commit silently overwrites the first (a lost update). Optimistic locking detects the conflict:

Java
@Version private long version;     // Hibernate adds "AND version = ?" to every UPDATE/DELETE and increments it
SQL
UPDATE orders SET status = ?, version = 8 WHERE id = 42 AND version = 7;
-- 0 rows updated → someone else changed it → OptimisticLockException (Spring: ObjectOptimisticLockingFailureException)

Handling it:

  • In APIs: map to 409 Conflict or 412 Precondition Failed, and expose the version as an ETag with If-Match (chapter 45) so clients can detect conflicts end to end, even across separate requests where the entity was detached.
  • In background jobs: retry the whole transaction (re-read, re-apply, commit) with a bounded number of attempts (chapter 52; Spring's @Retryable around the transactional method, outside the transaction).
  • Pessimistic locking for high-contention rows where retries would thrash: @Lock(LockModeType.PESSIMISTIC_WRITE) → SELECT … FOR UPDATE, with a lock timeout (jakarta.persistence.lock.timeout). Use SKIP LOCKED for work queues in a table (SELECT … FOR UPDATE SKIP LOCKED). Keep these transactions very short.
  • Atomic conditional updates avoid read-modify-write races entirely for simple cases: UPDATE stock SET qty = qty - :n WHERE sku = :sku AND qty >= :n (check the affected row count).

Batching

Inserting 10,000 rows one statement at a time means 10,000 network round trips. JDBC batching sends many statements in one round trip:

YAML
spring.jpa.properties.hibernate:
  jdbc.batch_size: 50
  order_inserts: true          # group inserts by entity type so they batch
  order_updates: true
  jdbc.batch_versioned_data: true

Caveats:

  • GenerationType.IDENTITY disables insert batching, because Hibernate must execute each INSERT to learn its ID. Use SEQUENCE with a pooled allocation size, or assigned UUIDs.
  • PostgreSQL: add reWriteBatchedInserts=true to the JDBC URL so the driver rewrites batches into multi-row INSERT … VALUES (…), (…), often several times faster.
  • Large batch jobs: flush and clear the persistence context every N entities to bound memory, or use StatelessSession, JdbcClient/JdbcTemplate.batchUpdate, or the database's bulk loading path (COPY in PostgreSQL via CopyManager).
  • Spring Data's saveAll doesn't batch by itself. It relies on these Hibernate settings.

Connection pools

Opening a database connection costs a TCP handshake, TLS, authentication and server-side session setup: milliseconds to tens of milliseconds, plus server memory (PostgreSQL forks a process per connection). Pools keep a set of open connections and lend them out. HikariCP is Spring Boot's default.

YAML
spring.datasource.hikari:
  maximum-pool-size: 10            # the most important setting
  minimum-idle: 10                 # fixed-size pool (recommended by HikariCP)
  connection-timeout: 2000         # ms to wait for a free connection before failing (fail fast, not hang)
  max-lifetime: 1800000            # retire connections before DB/proxy/firewall idle timeouts kill them
  keepalive-time: 300000
  leak-detection-threshold: 20000  # log a stack trace when a connection is held > 20 s (development and diagnosis)

Sizing: more connections isn't faster. The database has a fixed number of cores and disks, and past a small number of concurrent queries, contention (locks, CPU switching, cache thrashing) makes everything slower. HikariCP's well-known starting formula is connections ≈ (core_count × 2) + effective_spindle_count, often 10–20 per service instance. Then:

  • Total across instances matters: 30 pods × 20 connections = 600 connections to one PostgreSQL server, which is too many. Use a server-side pooler (PgBouncer, RDS Proxy) in transaction mode, or reduce per-pod pools.
  • Virtual threads don't change this: thousands of virtual threads will queue on the pool, which is correct behaviour (the pool is your bulkhead), but set connection-timeout so requests fail fast instead of piling up.
  • Watch the pool metrics (Micrometer exposes hikaricp.connections.active, pending and acquire time). Pending > 0 and high acquire times mean the pool is saturated. The cause is usually slow queries or long transactions (remote calls inside transactions, OSIV), not too few connections.
  • REQUIRES_NEW inside a transaction needs two connections per request. Under load, every request can hold one connection and wait for a second, and the pool deadlocks.

Persistence across languages

Other ecosystems

Ecosystem Main tools Notable design choices
C# / .NET EF Core (an ORM with a change tracker, LINQ queries, migrations), Dapper (a micro-ORM: SQL + mapping) LINQ queries are translated to SQL. Include() for eager loading; lazy loading is opt-in (proxies). AsNoTracking() for read-only. Split queries to avoid Cartesian explosion. Compiled models for startup
Python SQLAlchemy 2.0 (Core: an SQL expression language; ORM: Session unit of work), Django ORM, SQLModel (on FastAPI) The Session is a unit of work with an identity map, like JPA. Loader strategies per query (selectinload, joinedload, raiseload); async support
Go database/sql + pgx, sqlc (write SQL; generate type-safe Go), sqlx, GORM, ent (schema-as-code graph ORM), Bun The culture favours SQL-first (sqlc). sql.DB is a pool (SetMaxOpenConns, SetConnMaxLifetime). Transactions are explicit tx objects passed around (no ambient transactions)
Rust sqlx (async; query! macros verify SQL against the real schema at compile time), Diesel (a type-safe query DSL, sync with an async variant), SeaORM (async ORM) Compile-time checked SQL catches typos and type mismatches before running. No lazy loading
Elixir Ecto: Repo + Schemas + Changesets (validation and casting) + composable Ecto.Query Explicit preloading only (no lazy loading), no identity map or dirty-checking session. Updates go through changesets that record exactly which fields changed. Transactions with Repo.transaction/Ecto.Multi
TypeScript Prisma (schema file → generated client), Drizzle (SQL-like, type-safe), TypeORM, Kysely (query builder) Prisma batches relation loads (dataloader-style) to avoid N+1
C / C++ / Zig libpq, SQLite C API, ODBC; sqlpp11, SOCI (C++); zig-pg Mostly SQL + manual mapping

The spectrum runs from SQL-first (jOOQ, sqlc, sqlx, Dapper, JdbcClient: you write and see the SQL, and tools add type safety) to object-first (Hibernate, EF Core, SQLAlchemy ORM, Django: you manipulate objects, and the ORM generates SQL and tracks changes). Object-first is productive for complex write-side domain models with aggregates. SQL-first is predictable for queries, reporting and performance-critical paths. Mature teams use both deliberately, and in every case they look at the generated SQL and the query plans (Vol. 4).

Lab: the persistence problems behind most incidents

JDK 21, PostgreSQL 16 on the same machine, PostgreSQL JDBC driver 42.7.3. Data: 50 dishes, 200 orders with 4 lines each. Every query crosses only the loopback interface, so these numbers are the best case; in production each round trip adds the network's 0.2–1 ms.

Experiment 1: N+1 queries

Java
// N+1: one query for the orders, then one per order (what lazy loading does behind a loop)
for (long id : orderIds) q(c, "SELECT l.qty, d.name FROM order_line l JOIN dish d ON d.id = l.dish_id WHERE l.order_id = ?", id);
// one JOIN
q(c, "SELECT o.id, l.qty, d.name FROM orders o JOIN order_line l ON l.order_id = o.id JOIN dish d ON d.id = l.dish_id ORDER BY o.id");
// two queries: the orders, then all their lines at once
q(c, "SELECT … FROM order_line l JOIN dish d … WHERE l.order_id = ANY(?)", ids);
Text
200 orders with their lines: N+1 201 queries 47.6 ms | one JOIN 1 query 1.1 ms | orders + one IN-list query 2 queries 1.1 ms | lines 800/800/800

Same 800 lines, 43× slower with N+1, even on localhost; with a 0.5 ms network round trip it would be about 150 ms for one page, and the database spends its time parsing and planning 201 tiny queries. In JPA this appears whenever code loops over entities and touches a lazy association (order.getLines()), including inside JSON serialisation of entities. The fixes map to the last two queries: a fetch join (JOIN FETCH in JPQL, or @EntityGraph) or batch fetching (@BatchSize, or hibernate.default_batch_fetch_size, which loads lazy collections with IN lists). Detect it with SQL statement counts in tests (Hibernate statistics, datasource-proxy, or asserting query counts), not by reading code.

Experiment 2: writing 10,000 rows

Text
one statement per autocommit:          2275 ms
one transaction, one statement each:    208 ms
JDBC batch (addBatch/executeBatch):      89 ms
batch + reWriteBatchedInserts=true:      50 ms
COPY FROM STDIN:                          20 ms

Autocommit made every row its own transaction, each waiting for the write-ahead log to be flushed to disk: over 100× slower than COPY. One transaction removed the flushes; batching removed most round trips; the PostgreSQL driver's reWriteBatchedInserts turns a batch into multi-row INSERT … VALUES (…), (…) statements; COPY streams rows in the database's bulk-load format. In Hibernate, batching needs hibernate.jdbc.batch_size set and an id strategy that doesn't need a round trip per row (sequences with an allocation size, not IDENTITY), and order inserts and updates for it to apply. For imports and migrations, use COPY or the database's bulk tools rather than the ORM.

Experiment 3: connections are expensive

Text
100 × SELECT 1: new connection each time 719 ms (7.19 ms each) | one reused connection 3.4 ms (0.03 ms each)

Opening a PostgreSQL connection means a TCP handshake, authentication and the server forking a backend process, here 7 ms, about 200× the cost of the query itself (and much more with TLS across a network). That's why every application uses a connection pool (HikariCP is Spring Boot's default): a fixed set of open connections that requests borrow and return. Size it small. PostgreSQL's throughput peaks at a few connections per CPU core; HikariCP's guidance starts from cores × 2 + effective disks, typically 10–20 per instance, and the total across all instances must stay under the server's max_connections (or go through PgBouncer). With virtual threads, thousands of requests may wait for those 10 connections: that's correct (the pool is the bulkhead), as long as connectionTimeout makes them fail fast instead of piling up.

Experiment 4: lost updates and optimistic locking

The customer cancels order 7 while the kitchen, which loaded it a moment earlier, marks it as being prepared:

Text
without versions: customer cancels, kitchen marks preparing → final status PREPARING (the cancellation is lost)
with a version column: first update changed 1 row, second changed 0 rows → conflict detected; final status CANCELLED v1
SQL
UPDATE orders SET status = ?, version = version + 1 WHERE id = 7 AND version = ?

Both writers read version 0. The first update matched and bumped it to 1; the second found no row with version 0 and changed nothing, which the application treats as a conflict (reload, then retry or tell the user). This is exactly what JPA's @Version does, throwing OptimisticLockException (Spring: ObjectOptimisticLockingFailureException), and it's the database half of chapter 45's ETag and If-Match mechanism; the version becomes the ETag.

Experiment 5: read-modify-write under concurrency

Eight threads each add 1 to a balance 100 times:

Text
read, add in Java, write:               balance 120 (expected 800) in 655 ms
UPDATE balance = balance + 1:           balance 800 (expected 800) in 345 ms
SELECT … FOR UPDATE, then write:        balance 800 (expected 800) in 712 ms

Reading a value, computing in Java and writing it back lost 85% of the increments: chapter 38's race condition, now between database sessions, and PostgreSQL's default READ COMMITTED isolation doesn't prevent it. An atomic UPDATE … SET balance = balance + 1 lets the database serialise the change and was also the fastest; SELECT … FOR UPDATE locks the row for the rest of the transaction (pessimistic locking) and suits logic too complex for one statement. Other correct options are optimistic locking with retries (experiment 4) or REPEATABLE READ/SERIALIZABLE isolation with retry on serialisation failures (Volume 4 explains each anomaly). In JPA, loading an entity, changing a field and saving it is precisely the first pattern, so counters, stock levels and balances need a version, a lock, or an atomic update query.

Try it yourself

  1. Add a 1 ms artificial delay per query (run PostgreSQL in another container, or wrap the connection) and repeat experiment 1. How does the N+1 time scale?
  2. Repeat experiment 2's batch with batch sizes 10, 100, 1,000 and 10,000. Where do returns diminish?
  3. Use pg_stat_activity to watch the connections experiment 3 opens, then build a 5-connection pool with a BlockingQueue<Connection> and measure 100 virtual threads sharing it.
  4. Repeat experiment 5 at SERIALIZABLE isolation and handle SQLSTATE 40001 with a retry loop. How many retries happen?

Revision sheet: persistence

Key ideas

  • Stack: JDBC → JdbcClient/JdbcTemplate → JPA (Hibernate 7) → Spring Data repositories; all share connections, transactions and SQL.
  • JDBC: connections from a pool, prepared statements, result sets, try-with-resources, SQLSTATE codes, batching, COPY.
  • JPA: entities, ids and generators, associations (owning side, mappedBy), embeddables, inheritance strategies; entity states (transient, managed, detached, removed); the persistence context as identity map and unit of work; flush modes; dirty checking.
  • Loading: lazy by default for collections; N+1; fetch joins, entity graphs, batch fetching; projections (interfaces, records, DTO queries) for reads; pagination with joins (two-step queries).
  • Transactions: @Transactional propagation, read-only hints, rollback rules (unchecked by default), isolation levels; keep them short; no remote calls inside.
  • Concurrency: optimistic locking (@Version), pessimistic locks (FOR UPDATE, SKIP LOCKED for queues), atomic updates.
  • Pools: HikariCP sizing (small, per-core), timeouts, leak detection; PgBouncer modes.
  • Elsewhere: Go database/sql with sqlc or GORM, .NET EF Core and Dapper, Python SQLAlchemy and Django ORM, Rust sqlx and Diesel, Node Prisma, Drizzle and Knex, Ecto in Elixir.

Numbers to remember

  • Lab: N+1 (201 queries) 47.6 ms vs one join 1.1 ms on localhost; 10,000 inserts: 2,275 ms autocommit, 89 ms batched, 20 ms COPY; opening a connection 7.2 ms vs 0.03 ms per query reused; read-modify-write lost 85% of concurrent increments.
  • PostgreSQL error codes: 23505 unique, 23503 foreign key, 23514 check, 40001 serialisation failure, 40P01 deadlock.

Pitfalls

  • Lazy associations touched in loops or during serialisation (N+1); open-session-in-view hiding it (disable spring.jpa.open-in-view).
  • IDENTITY ids preventing insert batching; saving entities one by one in big loops.
  • @Transactional on private methods or self-invoked methods; catching exceptions inside and committing partial work.
  • Long transactions holding locks and connections (remote calls inside them).
  • Read-modify-write without versions or locks; entities with mutable equals/hashCode on generated ids.
  • Oversized pools; no connectionTimeout; no statement timeouts.

Glossary

  • Persistence context: the set of managed entities in a unit of work.
  • Flush: synchronising pending changes to the database (before commit or queries).
  • Fetch join: a join that loads an association in the same query.
  • Optimistic locking: detecting concurrent changes with a version check at write time.
  • Connection pool: reusable open database connections.
  • Projection: querying only the fields a use case needs.